diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Chashme Baddoor marathi movie mp4 hd free download Laugh out loud with Ali Zafar Taapsee Pannu and Siddharth.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Chashme Baddoor marathi movie mp4 hd free download Laugh out loud with Ali Zafar Taapsee Pannu and Siddharth.md deleted file mode 100644 index 37ca6977bb458d3db108413e55164023cf94dd9d..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Chashme Baddoor marathi movie mp4 hd free download Laugh out loud with Ali Zafar Taapsee Pannu and Siddharth.md +++ /dev/null @@ -1,147 +0,0 @@ -
-

Chashme Baddoor: A Hilarious Comedy Movie in Marathi

-

Introduction

-

If you are looking for a fun and entertaining movie to watch with your friends or family, you should check out Chashme Baddoor. It is a Marathi comedy movie that was released in 2013. It is a remake of the 1981 Hindi movie of the same name, which was directed by Sai Paranjape and starred Farooq Shaikh, Deepti Naval, Rakesh Bedi, and Ravi Baswani.

-

In this article, we will tell you everything you need to know about Chashme Baddoor, including what it is about, who are the main actors and characters, why you should watch it, and how to watch it online for free.

-

Chashme Baddoor marathi movie mp4 hd free download


Download Filehttps://byltly.com/2uKwgN



-

What is Chashme Baddoor?

-

Chashme Baddoor is a comedy movie that revolves around three friends and roommates who are studying at Delhi University. Siddharth (played by Ali Zafar) is a studious and sincere guy who is preparing for his PhD. Omi (played by Divyendu Sharma) and Jai (played by Siddharth) are lazy and flirtatious guys who are always chasing girls and having fun.

-

One day, they see a new girl in their neighborhood, Seema (played by Taapsee Pannu), who is a salesgirl for Chamko washing powder. Omi and Jai try to impress her with their tricks, but they fail miserably. Siddharth, on the other hand, falls in love with her at first sight and starts a relationship with her.

-

When Omi and Jai find out about this, they feel jealous and betrayed by their friend. They decide to break up their relationship by lying to Seema that Siddharth is already married and has a child. They also lie to Siddharth that Seema is a notorious criminal who is wanted by the police.

-

Will their plan succeed? Will Siddharth and Seema find out the truth? Will their friendship survive this test? You will have to watch the movie to find out.

-

Who are the main actors and characters?

-

The movie has a talented cast of actors who have done justice to their roles. Here are some of the main actors and characters in the movie:

- -

Why you should watch Chashme Baddoor

-

There are many reasons why you should watch Chashme Baddoor. Here are some of them:

-

It is a remake of a classic comedy movie

-

The original Chashme Baddoor was released in 1981 and was directed by Sai Paranjape. It was one of the most successful comedy movies of that time and received critical acclaim for its witty script, realistic characters, and hilarious situations. It also had some memorable songs composed by Raj Kamal and sung by Yesudas, Hemlata, Shailendra Singh, Anand Kumar C., etc.

-

Chashme Baddoor Marathi film HD online watch
-Chashme Baddoor 2013 Marathi movie free download mp4
-Watch Chashme Baddoor full movie HD Marathi
-Download Chashme Baddoor Marathi comedy film in HD quality
-Chashme Baddoor Marathi movie HD 1080p free download
-How to watch Chashme Baddoor Marathi movie online for free
-Chashme Baddoor Marathi film mp4 download link
-Chashme Baddoor full movie in Marathi HD download
-Chashme Baddoor Marathi movie free streaming HD
-Download Chashme Baddoor Marathi movie HD 720p
-Chashme Baddoor Marathi film download mp4 high quality
-Watch Chashme Baddoor Marathi comedy movie HD online
-Chashme Baddoor full movie Marathi HD free download
-Chashme Baddoor Marathi movie HD watch online free
-Download Chashme Baddoor 2013 Marathi film in HD mp4
-Chashme Baddoor Marathi movie HD download link
-Watch Chashme Baddoor full movie in Marathi HD online
-Chashme Baddoor Marathi film free download mp4 HD
-Chashme Baddoor Marathi comedy movie HD online watch
-Download Chashme Baddoor full movie Marathi HD
-Chashme Baddoor Marathi movie download mp4 HD quality
-Watch Chashme Baddoor 2013 Marathi film HD online free
-Chashme Baddoor full movie in Marathi free download mp4 HD
-Chashme Baddoor Marathi film HD streaming online
-Download Chashme Baddoor Marathi comedy movie in HD mp4
-Chashme Baddoor Marathi movie free download HD 1080p
-Watch Chashme Baddoor full movie HD in Marathi online
-Chashme Baddoor Marathi film download link mp4 HD
-Chashme Baddoor 2013 Marathi movie HD watch online
-Download Chashme Baddoor full movie in Marathi mp4 HD
-Chashme Baddoor Marathi movie download HD 720p free
-Watch Chashme Baddoor Marathi film online for free in HD
-Chashme Baddoor full movie Marathi download mp4 HD quality
-Chashme Baddoor Marathi comedy film free streaming HD online
-Download Chashme Baddoor 2013 Marathi movie in HD quality mp4
-Watch Chashme Baddoor full movie online free in Marathi HD
-Download link for Chashme Baddoor Marathi film mp4 HD
-Watch online Chashme Baddoor 2013 Marathi comedy movie in HD
-Free download of Chashme Baddoor full movie in Marathi mp4 HD
-Online streaming of Chashme Baddoor Marathi film in HD quality
-Download and watch Chashme Baddoor 2013 Marathi movie in HD mp4
-Watch and download Chashme Baddoor full movie in Marathi HD quality
-Free online watch of Chashme Baddoor 2013 comedy film in Marathi
-Free online download of Chashme Baddoor full comedy movie in Marathi
-Watch or download Chashme Baddoor 2013 film in Marathi mp4 format

-

The remake pays tribute to the original movie by retaining some of its scenes and dialogues. It also adds some new twists and turns to make it more contemporary and appealing to the modern audience. The remake also has some catchy songs composed by Sajid-Wajid and sung by Ali Zafar, Sonu Nigam, Shreya Ghoshal Wajid Khan Neuman Pinto etc.

-

It has a lot of funny scenes and dialogues

-

The movie is full of comedy scenes that will make you laugh out loud. Some of them are:

- -

The movie also has some witty dialogues that will make you chuckle. Some of them are:

- -

It has a good message about friendship and love

-

The movie is not just a comedy, but also a heartwarming story about friendship and love. It shows how true friends stick together through thick and thin, and how they support each other in times of need. It also shows how love can overcome misunderstandings and obstacles, and how it can bring happiness and peace to one's life.

-

The movie also has some emotional scenes that will touch your heart. Some of them are:

- -

How to watch Chashme Baddoor online for free

-

If you are wondering how to watch Chashme Baddoor online for free, you have several options. Here are some of them:

-

Netflix

-

Netflix is one of the most popular streaming platforms in the world. It has a huge collection of movies and shows in different languages and genres. You can watch Chashme Baddoor on Netflix with a subscription. You can also get a free trial for 30 days if you are a new user.

-

To watch Chashme Baddoor on Netflix, you need to follow these steps:

-
    -
  1. Go to https://www.netflix.com/ and sign up for an account or log in if you already have one.
  2. -
  3. Search for Chashme Baddoor in the search bar or browse through the categories.
  4. -
  5. Click on the movie title and enjoy watching it.
  6. -
-

Desi Cinemas

-

Desi Cinemas is a website that offers free streaming of Bollywood movies online. It has a good collection of movies in HD quality and with English subtitles. You can watch Chashme Baddoor on Desi Cinemas without any registration or subscription.

-

To watch Chashme Baddoor on Desi Cinemas, you need to follow these steps:

-
    -
  1. Go to https://desicinemas.tv/ and search for Chashme Baddoor in the search bar or browse through the categories.
  2. -
  3. Click on the movie title and choose a server to stream it from.
  4. -
  5. Enjoy watching the movie.
  6. -
-

JustWatch

-

JustWatch is a website that helps you find where to watch movies and shows online. It shows you the availability and price of different streaming platforms for any movie or show you want to watch. You can use JustWatch to find out where to watch Chashme Baddoor online for free or for a low cost.

-

To use JustWatch, you need to follow these steps:

-
    -
  1. Go to https://www.justwatch.com/ and select your country from the menu.
  2. -
  3. Search for Chashme Baddoor in the search bar or browse through the categories.
  4. -
  5. Click on the movie title and see the list of streaming platforms where you can watch it.
  6. -
  7. Select the platform that suits your preference and budget, and click on the link to go to its website.
  8. -
  9. Watch the movie on the chosen platform.
  10. -
-

Conclusion

-

In conclusion, Chashme Baddoor is a comedy movie that you should not miss. It is a remake of a classic movie that has been updated with new twists and turns. It has a talented cast of actors who have delivered hilarious performances. It has a lot of funny scenes and dialogues that will make you laugh out loud. It also has a good message about friendship and love that will touch your heart.

-

If you want to watch Chashme Baddoor online for free, you have several options such as Netflix, Desi Cinemas, and JustWatch. You can choose any of them according to your convenience and preference. You can also download the movie from various websites if you want to watch it offline.

-

So what are you waiting for? Grab your popcorn and your friends, and watch Chashme Baddoor online for free. You will surely have a great time watching this movie.

-

FAQs

-

Here are some frequently asked questions about Chashme Baddoor:

-
    -
  1. Q: Is Chashme Baddoor a remake of a movie?
    -A: Yes, Chashme Baddoor is a remake of the 1981 Hindi movie of the same name, which was directed by Sai Paranjape and starred Farooq Shaikh, Deepti Naval, Rakesh Bedi, and Ravi Baswani.
  2. -
  3. Q: Who are the main actors and characters in Chashme Baddoor?
    -A: The main actors and characters in Chashme Baddoor are Ali Zafar as Siddharth, Taapsee Pannu as Seema, Siddharth as Jai, Divyendu Sharma as Omi, Rishi Kapoor as Mr. Joseph Furtado, and Anupam Kher as Suryakant Paranjape and Lallan Miyan.
  4. -
  5. Q: What are some of the songs in Chashme Baddoor?
    -A: Some of the songs in Chashme Baddoor are "Har ek friend kamina hota hai", "Dhichkyaaon doom doom", "Early to bed and early to rise", and "Chamko chamko chamko".
  6. -
  7. Q: Where can I watch Chashme Baddoor online for free?
    -A: You can watch Chashme Baddoor online for free on Netflix, Desi Cinemas, or JustWatch. You can also download the movie from various websites if you want to watch it offline.
  8. -
  9. Q: What is the message of Chashme Baddoor?
    -A: The message of Chashme Baddoor is that friendship and love are precious and should not be ruined by jealousy and lies. It also shows that true friends and lovers will always stand by each other and overcome any difficulties.
  10. -
-

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Car Parking Multiplayer Mod Apk Drive Park and Customize 70 Vehicles with Everything Unlocked.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Car Parking Multiplayer Mod Apk Drive Park and Customize 70 Vehicles with Everything Unlocked.md deleted file mode 100644 index 628480ec8584ae0fef9390bbd7828332f2cd074b..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Car Parking Multiplayer Mod Apk Drive Park and Customize 70 Vehicles with Everything Unlocked.md +++ /dev/null @@ -1,88 +0,0 @@ - -

Car Parking Multiplayer Mod APK Unlocked Everything New Version

-

Do you love driving and parking games? Do you want to experience the thrill of realistic car physics, open world map, multiplayer mode, customization options, and different game modes? If yes, then you should try Car Parking Multiplayer, one of the most popular and realistic car parking simulation games for Android devices. And if you want to enjoy the game with unlimited money, gold, cars, items, and no ads, then you should download Car Parking Multiplayer Mod APK, the modified version of the game that gives you everything unlocked for free. In this article, we will tell you what is Car Parking Multiplayer, what are its features, why you should download Car Parking Multiplayer Mod APK, and how to download and install it on your device.

-

What is Car Parking Multiplayer?

-

Car Parking Multiplayer is a car parking simulation game developed by olzhass, a game studio that specializes in realistic driving and parking games. The game has more than 100 million downloads on Google Play Store and has an average rating of 4.3 out of 5 stars. The game lets you drive and park various types of cars, from sedans to sports cars, from trucks to buses, from classic cars to modern cars. You can choose from more than 150 different cars, each with its own characteristics and features. You can also customize and tune your cars according to your preferences, changing the color, wheels, suspension, engine, turbo, exhaust, and more.

-

car parking multiplayer mod apk unlocked everything new version


Download File ⚹⚹⚹ https://urlin.us/2uSTgz



-

Features of Car Parking Multiplayer

-

Car Parking Multiplayer is not just a simple car parking game. It has many features that make it stand out from other similar games. Here are some of the features of Car Parking Multiplayer:

-

Realistic car physics and graphics

-

The game uses advanced car physics and graphics to create a realistic driving and parking experience. You can feel the weight, speed, acceleration, braking, steering, and suspension of each car. You can also see the details of each car model, such as the interior, exterior, lights, mirrors, doors, windows, etc. The game also has realistic sound effects for each car engine, horn, tire screech, collision, etc.

-

Open world map and multiplayer mode

-

The game has an open world map that you can explore freely. You can drive around the city streets, highways, parking lots, airports, deserts, forests, beaches, etc. You can also interact with other players in the multiplayer mode. You can chat with them using voice or text messages. You can also join or create your own online room with up to 100 players. You can race with them, challenge them to parking competitions, or just have fun together.

-

Customization and tuning options

-

The game gives you a lot of options to customize and tune your cars. You can change the color of your car using a color picker or choose from predefined colors. You can also change the wheels of your car using different rims and tires. You can also modify the suspension height, camber angle, wheel size, etc. You can also upgrade the engine performance of your car using turbo boosters, nitrous oxide injectors, etc. You can also change the exhaust sound of your car using different mufflers.

-

Different game modes and challenges

-

The game has different game modes and challenges that you can play according to your mood and skill level. You can play the classic parking mode where you have to park your car in a designated spot without hitting any obstacles or other cars. You can also play the free driving mode where you can drive around the map without any restrictions or objectives. You can also play the drift mode where you have to perform drifts and earn points. You can also play the police mode where you can chase or be chased by the police cars. You can also play the zombie mode where you have to survive the zombie apocalypse by driving and shooting zombies. You can also play the delivery mode where you have to deliver goods from one place to another. You can also play the taxi mode where you have to pick up and drop off passengers. You can also play the tow truck mode where you have to tow broken or illegally parked cars.

-

Why download Car Parking Multiplayer Mod APK?

-

Car Parking Multiplayer is a fun and addictive game, but it also has some limitations and drawbacks. For example, you need a lot of money and gold to buy, upgrade, and customize your cars. You also need to watch ads to get some rewards or skip some levels. You also need to root your device to access some features or items. These things can make the game less enjoyable and frustrating for some players. That's why you should download Car Parking Multiplayer Mod APK, the modified version of the game that gives you everything unlocked for free.

-

Benefits of Car Parking Multiplayer Mod APK

-

Car Parking Multiplayer Mod APK is a hacked version of the game that has many benefits over the original version. Here are some of the benefits of Car Parking Multiplayer Mod APK:

-

Unlimited money and gold

-

With Car Parking Multiplayer Mod APK, you don't have to worry about running out of money and gold. You will get unlimited money and gold in your account as soon as you start the game. You can use them to buy any car you want, upgrade it, customize it, and tune it. You can also use them to buy any item you need, such as fuel, repair kits, weapons, etc.

-

car parking multiplayer mod apk latest version with all unlocked
-download car parking multiplayer mod apk unlimited money and cars
-car parking multiplayer mod apk free download for android no root
-how to install car parking multiplayer mod apk with obb file
-car parking multiplayer mod apk hack online generator
-car parking multiplayer mod apk 2023 update new features
-car parking multiplayer mod apk revdl rexdl android 1
-car parking multiplayer mod apk offline mode enabled
-car parking multiplayer mod apk unlimited gold and diamonds
-car parking multiplayer mod apk premium vip membership
-car parking multiplayer mod apk best settings for realistic graphics
-car parking multiplayer mod apk custom maps and vehicles
-car parking multiplayer mod apk cheats codes and tips
-car parking multiplayer mod apk gameplay video review
-car parking multiplayer mod apk download link in description
-car parking multiplayer mod apk full version cracked
-car parking multiplayer mod apk mega mod menu
-car parking multiplayer mod apk no ads and surveys
-car parking multiplayer mod apk original vs modified comparison
-car parking multiplayer mod apk safe and secure download
-car parking multiplayer mod apk unlimited fuel and nitro
-car parking multiplayer mod apk new cars and skins added
-car parking multiplayer mod apk fun and challenging missions
-car parking multiplayer mod apk high quality sound effects and music
-car parking multiplayer mod apk support all android devices
-car parking multiplayer mod apk easy and fast installation process
-car parking multiplayer mod apk unlock everything without verification
-car parking multiplayer mod apk latest bug fixes and improvements
-car parking multiplayer mod apk realistic physics and controls
-car parking multiplayer mod apk social media integration and chat feature
-car parking multiplayer mod apk low mb size and battery consumption
-car parking multiplayer mod apk unlimited xp and level up fast
-car parking multiplayer mod apk new modes and events added regularly
-car parking multiplayer mod apk 3d hd graphics and animation
-car parking multiplayer mod apk user friendly interface and design
-car parking multiplayer mod apk unlimited coins and gems generator
-car parking multiplayer mod apk pro version unlocked for free
-car parking multiplayer mod apk anti ban and virus protection
-car parking multiplayer mod apk online and offline gameplay options
-car parking multiplayer mod apk compatible with all android versions

-

All cars and items unlocked

-

With Car Parking Multiplayer Mod APK, you don't have to wait or work hard to unlock all the cars and items in the game. You will get access to all the cars and items from the beginning of the game. You can choose from more than 150 different cars, each with its own features and characteristics. You can also use any item you want, such as turbo boosters, nitrous oxide injectors, mufflers, etc.

-

No ads and no root required

-

With Car Parking Multiplayer Mod APK, you don't have to watch annoying ads or root your device to enjoy the game. The mod apk file has no ads and no root requirement. You can play the game without any interruptions or risks. You can also update the game easily without losing your progress or data.

-

How to download and install Car Parking Multiplayer Mod APK?

-

Downloading and installing Car Parking Multiplayer Mod APK is very easy and simple. Just follow these steps:

-

Step 1: Download the mod apk file from a trusted source

-

The first step is to download the mod apk file from a trusted source. You can use this link to download the latest version of Car Parking Multiplayer Mod APK for free. The file size is about 300 MB and it is safe and virus-free.

-

Step 2: Enable unknown sources on your device settings

-

The second step is to enable unknown sources on your device settings. This will allow you to install apps from sources other than Google Play Store. To do this, go to your device settings > security > unknown sources > enable.

-

Step 3: Install the mod apk file and enjoy the game

-

The third step is to install the mod apk file and enjoy the game. To do this, locate the downloaded mod apk file on your device storage and tap on it. Follow the instructions on the screen and wait for the installation process to finish. Once done, open the game and start playing with everything unlocked for free.

-

Conclusion

-

Car Parking Multiplayer is one of the best car parking simulation games for Android devices. It has realistic car physics and graphics, open world map and multiplayer mode, customization and tuning options, different game modes and challenges, and more. However, if you want to enjoy the game with unlimited money, gold, cars, items, and no ads, then you should download Car Parking Multiplayer Mod APK, the modified version of the game that gives you everything unlocked for free. Just follow the steps above to download and install Car Parking Multiplayer Mod APK on your device and have fun.

Here are some FAQs that you might have about Car Parking Multiplayer Mod APK:

-

Q: Is Car Parking Multiplayer Mod APK safe to use?

-

A: Yes, Car Parking Multiplayer Mod APK is safe to use. It has no viruses, malware, or spyware. It also does not require root access or any permissions that might compromise your device security or privacy.

-

Q: Is Car Parking Multiplayer Mod APK compatible with my device?

-

A: Car Parking Multiplayer Mod APK is compatible with most Android devices that have Android 4.4 or higher. However, some devices might have compatibility issues due to different hardware or software specifications. If you encounter any problems while playing the game, you can contact the developer for support or try another device.

-

Q: Can I play Car Parking Multiplayer Mod APK online with other players?

-

A: Yes, you can play Car Parking Multiplayer Mod APK online with other players. The game has a multiplayer mode that allows you to join or create online rooms with up to 100 players. You can chat with them, race with them, challenge them, or just have fun together.

-

Q: Can I update Car Parking Multiplayer Mod APK to the latest version?

-

A: Yes, you can update Car Parking Multiplayer Mod APK to the latest version. However, you need to download and install the new mod apk file from the same source that you used before. You also need to uninstall the previous version of the game before installing the new one. You can also backup your game data before updating to avoid losing your progress or data.

-

Q: Can I request a new feature or report a bug for Car Parking Multiplayer Mod APK?

-

A: Yes, you can request a new feature or report a bug for Car Parking Multiplayer Mod APK. You can contact the developer through their email address or social media accounts. You can also leave a comment or feedback on the source website where you downloaded the mod apk file. The developer will try to respond to your request or fix the bug as soon as possible.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download queue xbox series x How to see and prioritize your game and app installations.md b/spaces/1phancelerku/anime-remove-background/Download queue xbox series x How to see and prioritize your game and app installations.md deleted file mode 100644 index 6ba8a739ba87eb568953d28aa33668d95df82145..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download queue xbox series x How to see and prioritize your game and app installations.md +++ /dev/null @@ -1,170 +0,0 @@ - -

How to Manage Your Download Queue on Xbox Series X

-

If you have an Xbox Series X, you probably want to download and play a lot of games and apps on your console. But sometimes, you may encounter some issues with your downloads, such as slow speed, errors, or interruptions. That's why it's important to know how to manage your download queue on Xbox Series X.

-

The download queue is where you can see the status of your game and app installations, as well as pause, cancel, or prioritize them. You can also launch a downloaded game or app from the queue or from a notification on your screen.

-

download queue xbox series x


Download 🆗 https://jinyurl.com/2uNO1d



-

In this article, we will show you how to view and manage your download queue on Xbox Series X, as well as how to troubleshoot some common problems with your game and app installations. We will also give you some tips on how to optimize your network bandwidth for game downloads.

-

How to View the Status of Your Game and App Installations

-

To access your download queue on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select My games & apps > See all.
  4. -
  5. Select Manage > Queue.
  6. -
-

Here, you can see the active downloads with a progress bar along the bottom of the game or app's tile. You can also see the estimated time remaining, the file size, and the download speed.

-

How to Pause, Cancel, or Prioritize Your Downloads

-

From the queue, you can also control your downloads using your controller and the on-screen prompts. Here are some options:

- -

You can also use the Sort by option to arrange your queue by name, size, or date added.

-

How to Launch a Downloaded Game or App

-

Once a game or app is fully downloaded and installed, you can launch it from the queue by selecting Play. You can also launch it from a notification that pops up on your screen when the installation is complete.

-

How to check download progress on Xbox Series X/S
-Xbox Series X download queue not working
-Xbox Series X download queue stuck
-How to manage download queue on Xbox Series X
-Xbox Series X download queue slow
-How to cancel download queue on Xbox Series X
-Xbox Series X download queue error
-How to pause download queue on Xbox Series X
-Xbox Series X download queue limit
-How to prioritize download queue on Xbox Series X
-Xbox Series X download queue full
-How to clear download queue on Xbox Series X
-Xbox Series X download queue issues
-How to resume download queue on Xbox Series X
-Xbox Series X download queue missing
-How to view download queue on Xbox Series X
-Xbox Series X download queue not showing
-How to speed up download queue on Xbox Series X
-Xbox Series X download queue order
-How to change download queue on Xbox Series X
-Xbox Series X download queue problem
-How to fix download queue on Xbox Series X
-Xbox Series X download queue size
-How to delete download queue on Xbox Series X
-Xbox Series X download queue update
-How to access download queue on Xbox Series X
-Xbox Series X download queue won't start
-How to move download queue on Xbox Series X
-Xbox Series X download queue location
-How to stop download queue on Xbox Series X
-Xbox Series X download queue offline
-How to restart download queue on Xbox Series X
-Xbox Series X download queue notification
-How to transfer download queue on Xbox Series X
-Xbox Series X download queue online
-How to install download queue on Xbox Series X
-Xbox Series X download queue hidden
-How to find download queue on Xbox Series X
-Xbox Series X download queue settings
-How to edit download queue on Xbox Series X
-Xbox Series X download queue tips
-How to optimize download queue on Xbox Series X
-Xbox Series X download queue guide
-How to troubleshoot download queue on Xbox Series X
-Xbox Series X download queue tricks

-

Alternatively, you can use the guide to launch a downloaded game or app. Just press the Xbox button Xbox button on your controller and select My games & apps > See all. Then, select the game or app you want to play from the list.

-

How to Troubleshoot Your Game and App Installations

-

Sometimes, you may encounter some issues with your game and app installations, such as slow speed, errors, or interruptions. Here are some common causes and solutions for these problems:

-

How to Check Your Internet Connection

-

Your internet connection is one of the most important factors that affect your download speed and performance. If your connection is weak, unstable, or slow, your downloads may take longer or fail.

-

To check your internet connection on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select Profile & system > Settings > General > Network settings.
  4. -
  5. Select Test network connection to see if you are connected to the internet.
  6. -
  7. Select Test network speed & statistics to see your download speed, upload speed, and latency.
  8. -
-

If you see any errors or warnings, follow the instructions on the screen to fix them. You may need to reboot your router, move closer to it, or use a wired connection instead of wireless.

How to Check Your Account and Storage Space

-

Another factor that may affect your game and app installations is your account and storage space. You need to make sure that you are signed in to the correct account and that you have enough storage space on your console or external drive for your downloads.

-

To check your account and storage space on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select Profile & system > Add or switch to see which account you are using. If you want to switch to a different account, select it from the list or add a new one.
  4. -
  5. Select My games & apps > See all > Manage > Storage devices to see how much storage space you have left on your console or external drive. If you need more space, you can delete some games or apps that you don't use, move them to another device, or add a new device.
  6. -
-

How to Restart Your Console

-

Sometimes, a simple restart can fix some issues with your game and app installations. Restarting your console can clear the cache, refresh the system, and resume your downloads.

-

To restart your console on Xbox Series X, follow these steps:

-
    -
  1. Press and hold the Xbox button Xbox button on your controller until the power menu appears.
  2. -
  3. Select Restart console > Restart.
  4. -
  5. Wait for your console to turn off and on again.
  6. -
  7. Check your download queue to see if your downloads are resumed or completed.
  8. -
-

How to Contact Xbox Support

-

If none of the above solutions work, you may need to contact Xbox support for further assistance. Xbox support can help you with troubleshooting, error codes, refunds, warranties, and more.

-

To contact Xbox support on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select Profile & system > Settings > System > Console info.
  4. -
  5. Note down your serial number and OS version.
  6. -
  7. Go to https://support.xbox.com/en-US/contact-us on your phone or computer.
  8. -
  9. Select Xbox Series X|S as your device and choose a topic and issue that matches your problem.
  10. -
  11. Follow the instructions on the screen to get help from a live agent, a chatbot, a community forum, or a self-help article.
  12. -

How to Manage Your Network Bandwidth for Game Downloads

-

Another way to improve your download speed and performance is to manage your network bandwidth for game downloads. Network bandwidth is the amount of data that can be transferred over your internet connection at a given time. The more bandwidth you use, the faster your downloads will be, but also the more likely you will experience lag or buffering when streaming or playing online games.

-

To manage your network bandwidth for game downloads on Xbox Series X, you can adjust your network settings to enable or disable automatic updates, set a download limit or schedule, or use a wired or wireless connection.

-

How to Enable or Disable Automatic Updates

-

Automatic updates are a feature that allows your console to keep your games and apps up to date without you having to manually check for updates. This can be convenient, but also consume a lot of bandwidth and slow down your other downloads.

-

To enable or disable automatic updates on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select Profile & system > Settings > System > Updates & downloads.
  4. -
  5. Select Keep my games & apps up to date to toggle the feature on or off.
  6. -
-

If you disable automatic updates, you will need to manually check for updates for your games and apps by going to My games & apps > See all > Manage > Updates.

-

How to Set a Download Limit or Schedule

-

A download limit or schedule is a feature that allows you to limit the amount of bandwidth used for downloads or schedule them for off-peak hours. This can help you avoid using up your data cap, reduce congestion on your network, and avoid interfering with your online gaming or streaming activities.

-

To set a download limit or schedule on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select Profile & system > Settings > System > Updates & downloads.
  4. -
  5. Select Download settings > Limit how much data I use for game and app downloads.
  6. -
  7. Select one of the options: Don't limit, Limit 2 GB per hour, Limit 5 GB per hour, Limit 10 GB per hour, Limit 25 GB per hour, or Limit 50 GB per hour.
  8. -
  9. Select Download settings > Schedule when I download game and app updates.
  10. -
  11. Select one of the options: Any time, During off-peak hours only, or During off-peak hours and when I'm not playing games.
  12. -
-

You can also customize your off-peak hours by selecting Download settings > Change my off-peak hours and choosing a start and end time.

How to Use a Wired or Wireless Connection

-

The type of connection you use for your console can also affect your download speed and performance. A wired connection is usually faster, more stable, and more secure than a wireless connection, but it requires a cable and a port on your router. A wireless connection is more convenient and flexible, but it can be affected by interference, distance, and other devices on your network.

-

To use a wired or wireless connection on Xbox Series X, follow these steps:

-
    -
  1. Press the Xbox button Xbox button on your controller to open the guide.
  2. -
  3. Select Profile & system > Settings > General > Network settings.
  4. -
  5. Select Set up wireless network to connect to a Wi-Fi network. You will need to enter your network name and password.
  6. -
  7. Select Advanced settings > Alternate MAC address to enter a MAC address for your console if your router requires it.
  8. -
  9. Select Advanced settings > IP settings to configure your IP address, subnet mask, gateway, and DNS servers if your network requires it.
  10. -
  11. Or, plug an Ethernet cable into the port on the back of your console and the port on your router. Your console will automatically detect the wired connection.
  12. -
-

Conclusion

-

Managing your download queue on Xbox Series X can help you enjoy your games and apps without any hassle. You can view and control your downloads, troubleshoot any issues, and optimize your network bandwidth for the best experience. Here are some tips and recommendations to remember:

- -

FAQs

-

Q: How do I download games and apps on Xbox Series X?

-

A: You can download games and apps on Xbox Series X from the Microsoft Store. To access the store, press the Xbox button Xbox button on your controller and select Store. Then, browse or search for the game or app you want and select Get or Buy. The game or app will be added to your download queue automatically.

-

Q: How do I check for updates for my games and apps on Xbox Series X?

-

A: You can check for updates for your games and apps on Xbox Series X by going to My games & apps > See all > Manage > Updates. Here, you can see which games and apps have available updates and select them to download them. You can also enable automatic updates to keep your games and apps up to date without checking manually.

-

Q: How do I delete games and apps on Xbox Series X?

-

A: You can delete games and apps on Xbox Series X by going to My games & apps > See all > Manage > Storage devices. Here, you can see how much space each game or app takes up on your console or external drive. Select one of them and choose Uninstall to delete it. You can also select Uninstall all to delete all games and apps on that device.

-

Q: How do I move games and apps between devices on Xbox Series X?

-

A: You can move games and apps between devices on Xbox Series X by going to My games & apps > See all > Manage > Storage devices. Here, you can see which games and apps are stored on your console or external drive. Select one of them and choose Move to move it to another device. You can also select Move all to move all games and apps from one device to another.

-

Q: How do I play games from an external drive on Xbox Series X?

-

A: You can play games from an external drive on Xbox Series X by plugging the drive into one of the USB ports on the back or front of your console. Your console will detect the drive and show you the games and apps that are stored on it. You can launch them from the guide or from My games & apps. You can also move them to your console or another external drive if you want.

-

Note that some games may require an update or optimization to run on Xbox Series X. You can check for these by going to My games & apps > See all > Manage > Updates > Optimized for Xbox Series X|S.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Explore the possibilities of melon playground a sandbox game for iOS and Android that is easy to play and hard to put down.md b/spaces/1phancelerku/anime-remove-background/Explore the possibilities of melon playground a sandbox game for iOS and Android that is easy to play and hard to put down.md deleted file mode 100644 index 0ab701407caef1574c6fb8002a82e476cb0d4ad0..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Explore the possibilities of melon playground a sandbox game for iOS and Android that is easy to play and hard to put down.md +++ /dev/null @@ -1,91 +0,0 @@ -
-

Melon Playground: A Fun and Creative Sandbox Game for iOS Devices

-

Do you like sandbox games where you can create your own scenarios and experiment with different items? Do you have an iOS device and want to find a fun and creative app to play with? If you answered yes to both questions, then you should check out Melon Playground, a simple but amazing sandbox game that will keep you entertained for hours.

-

What is Melon Playground?

-

A simple sandbox game where you create your own scenarios

-

Melon Playground is an indie game created by a developer named sliz. It is available on Android and iOS devices . The game is very simple: you have a scene where you can drag and drop various items from an inventory. You can then interact with these items in different ways, such as throwing them, shooting them, exploding them, or combining them. You can also change the gravity, time, weather, and other settings of the scene. The game has no rules or objectives; you are free to create whatever you want.

-

melon playground apk apple


Download File 🆗 https://jinyurl.com/2uNP6j



-

A wide variety of items at your disposal: melee weapons, guns, barrels, and more

-

The game offers a wide variety of items that you can use in your scenarios. You can find melee weapons such as swords, axes, hammers, knives, and bats; guns such as pistols, rifles, shotguns, snipers, and rocket launchers; barrels such as oil drums, gas tanks, water barrels, and explosive barrels; and other items such as cars, bikes, planes, helicopters, boats, animals, humans, zombies, aliens, robots, ragdolls, furniture, plants, food, drinks, balls, balloons, fireworks, and more. You can also customize the color and size of some items.

-

A free app with in-app purchases and no ads subscription option

-

The game is free to download from the App Store and does not require an internet connection to play. However, some items are locked behind in-app purchases that range from $0.99 to $4.99. You can also buy a no ads subscription for $3.49 per week that removes all ads from the game. The game does not have any pop-up ads or banners; only video ads that play when you load or save a scenario or when you exit the app.

-

How to play Melon Playground?

-

Download the app from the App Store and launch it on your device

-

Choose a map from the menu or create your own custom map

-

Once you launch the app, you will see a menu where you can choose a map to play on. There are 12 maps available in the game, each with a different theme and environment. You can choose from city, desert, forest, island, moon, ocean, playground, snow, space, swamp, volcano, and wasteland. You can also create your own custom map by selecting the blank map option and changing the terrain, skybox, and lighting.

-

melon playground app store download
-melon playground ios sandbox game
-melon playground apk for iphone
-melon playground no ads subscription
-melon playground file manager mod
-melon playground indie game sliz
-melon playground melee weapons guns
-melon playground create your own scenarios
-melon playground app privacy policy
-melon playground app support license
-melon playground twitter updates
-melon playground android and ios
-melon playground mobile application
-melon playground 17+ age rating
-melon playground free offers in-app purchases
-melon playground 4.5 stars ratings
-melon playground 333.1 mb size
-melon playground payge ltd developer
-melon playground macos 11.0 or later
-melon playground ios 12.0 or later
-melon playground barrels horror themes
-melon playground version 15.1.1 update
-melon playground stability improvement bugs fixes
-melon playground net energy gain experiment
-melon playground holy grail fusion mini sun
-melon playground korea superconducting tokamak advanced research facility
-melon playground nuclear fusion reaction 100 million degrees celsius
-melon playground seven times hotter than sun core
-melon playground sun core temperature kelvin
-melon playground new scientist article
-melon playground the sun news article
-melon playground yahoo news article
-melon playground wikipedia solar core page
-melon playground cornell university solar layers page
-melon playground nasa sun fact sheet page
-melon playground montana solar physics core page
-melon playground identifiers usage data tracking
-melon playground purchases location user content linked data
-melon playground diagnostics data not linked to identity
-melon playground frequent intense cartoon fantasy violence

-

Drag and drop items from the inventory to the scene and interact with them

-

After you choose a map, you will enter the scene where you can start creating your scenario. You can access the inventory by tapping on the backpack icon on the top right corner of the screen. You can scroll through the categories and items by swiping left or right on the inventory. To place an item on the scene, simply drag and drop it from the inventory. You can also tap on an item to see its name and description.

-

To interact with an item, you can tap on it or use the buttons on the bottom of the screen. You can throw an item by tapping on it and swiping in any direction. You can shoot an item by tapping on it and tapping on the target icon. You can explode an item by tapping on it and tapping on the bomb icon. You can combine two items by dragging one item over another item and tapping on the plus icon.

-

Use the buttons on the screen to move, rotate, scale, clone, delete, or freeze items

-

You can also modify the items on the scene by using the buttons on the left side of the screen. You can move an item by tapping on it and dragging it with your finger. You can rotate an item by tapping on it and using two fingers to twist it. You can scale an item by tapping on it and using two fingers to pinch or spread it. You can clone an item by tapping on it and tapping on the clone icon. You can delete an item by tapping on it and tapping on the trash icon. You can freeze an item by tapping on it and tapping on the freeze icon.

-

Save and load your scenarios or share them with other players online

-

You can save your scenarios by tapping on the save icon on the top left corner of the screen. You can name your scenario and choose a thumbnail for it. You can load your scenarios by tapping on the load icon next to the save icon. You can also share your scenarios with other players online by tapping on the share icon next to the load icon. You can upload your scenario to a server where other players can download it and rate it.

-

Why should you play Melon Playground?

-

It stimulates your imagination and creativity

-

Melon Playground is a game that lets you unleash your imagination and creativity. You can create any scenario you want with any items you want. You can make funny, scary, action-packed, or relaxing scenarios. You can make stories, jokes, experiments, or challenges. You can make anything you can think of with Melon Playground.

-

It offers endless possibilities and fun

-

Melon Playground is a game that offers endless possibilities and fun. You can play with different items and see how they react with each other. You can change the settings of the scene and see how they affect your scenario. You can explore different maps and discover new things. You can also download other players' scenarios and see what they have created.

-

It has positive reviews and ratings from users and critics

-

It is updated regularly with new features and improvements

-

Melon Playground is a game that is updated regularly with new features and improvements. The developer listens to the feedback and suggestions from the users and implements them in the game. The game has received several updates since its launch in 2020, adding new items, maps, settings, modes, and bug fixes. The developer also plans to add more content and features in the future, such as multiplayer mode, online chat, voice chat, VR support, and more.

-

Conclusion

-

Melon Playground is a great sandbox game for iOS devices that lets you create your own scenarios with various items

-

In conclusion, Melon Playground is a great sandbox game for iOS devices that lets you create your own scenarios with various items. You can use melee weapons, guns, barrels, cars, planes, animals, humans, zombies, aliens, robots, ragdolls, furniture, plants, food, drinks, balls, balloons, fireworks, and more to make your scenarios. You can also change the gravity, time, weather, and other settings of the scene to make it more interesting.

-

It is easy to play, free to download, and fun to explore

-

Melon Playground is easy to play, free to download, and fun to explore. You can download it from the App Store and play it offline or online. You can drag and drop items from the inventory to the scene and interact with them using simple gestures and buttons. You can also save and load your scenarios or share them with other players online.

-

It is a popular and well-made app that deserves your attention and support

-

Melon Playground is a popular and well-made app that deserves your attention and support. It has positive reviews and ratings from users and critics . It has been featured in several media outlets such as AppAdvice, Pocket Gamer, TouchArcade, iMore, 148Apps, AppSpy, Slide to Play, Gamezebo, Cult of Mac, Macworld, The Guardian, Mashable, TechCrunch, Wired, The Verge, Polygon, Kotaku, IGN, GameSpot, PC Gamer, Forbes, Business Insider, CNN, BBC News, The New York Times, The Wall Street Journal, TIME Magazine, and more. It is also updated regularly with new features and improvements by the developer.

-

If you are looking for a fun and creative sandbox game for your iOS device, you should definitely give Melon Playground a try. You will not regret it.

-

FAQs

-

What are the minimum requirements to play Melon Playground on iOS devices?

-

To play Melon Playground on iOS devices, you need iOS 12.0 or later or iPadOS 12.0 or later. You also need at least 300 MB of free storage space on your device.

-

How can I contact the developer of Melon Playground?

-

You can contact the developer of Melon Playground by sending an email to slizgames@gmail.com or by following him on Twitter @sliz_games.

-

How can I support the development of Melon Playground?

-

You can support the development of Melon Playground by buying in-app purchases or subscribing to no ads in the game. You can also rate and review the game on the App Store or share it with your friends.

-

How can I report a bug or a problem in Melon Playground?

-

You can report a bug or a problem in Melon Playground by sending an email to slizgames@gmail.com or by leaving a comment on the game's page on the App Store.

-

How can I suggest a new feature or an improvement for Melon Playground?

-

You can suggest a new feature or an improvement for Melon Playground by sending an email to slizgames@gmail.com or by leaving a comment on the game's page on the App Store.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/4Taps/SadTalker/src/audio2pose_models/discriminator.py b/spaces/4Taps/SadTalker/src/audio2pose_models/discriminator.py deleted file mode 100644 index 339c38e4812ff38a810f0f3a1c01812f6d5d78db..0000000000000000000000000000000000000000 --- a/spaces/4Taps/SadTalker/src/audio2pose_models/discriminator.py +++ /dev/null @@ -1,76 +0,0 @@ -import torch -import torch.nn.functional as F -from torch import nn - -class ConvNormRelu(nn.Module): - def __init__(self, conv_type='1d', in_channels=3, out_channels=64, downsample=False, - kernel_size=None, stride=None, padding=None, norm='BN', leaky=False): - super().__init__() - if kernel_size is None: - if downsample: - kernel_size, stride, padding = 4, 2, 1 - else: - kernel_size, stride, padding = 3, 1, 1 - - if conv_type == '2d': - self.conv = nn.Conv2d( - in_channels, - out_channels, - kernel_size, - stride, - padding, - bias=False, - ) - if norm == 'BN': - self.norm = nn.BatchNorm2d(out_channels) - elif norm == 'IN': - self.norm = nn.InstanceNorm2d(out_channels) - else: - raise NotImplementedError - elif conv_type == '1d': - self.conv = nn.Conv1d( - in_channels, - out_channels, - kernel_size, - stride, - padding, - bias=False, - ) - if norm == 'BN': - self.norm = nn.BatchNorm1d(out_channels) - elif norm == 'IN': - self.norm = nn.InstanceNorm1d(out_channels) - else: - raise NotImplementedError - nn.init.kaiming_normal_(self.conv.weight) - - self.act = nn.LeakyReLU(negative_slope=0.2, inplace=False) if leaky else nn.ReLU(inplace=True) - - def forward(self, x): - x = self.conv(x) - if isinstance(self.norm, nn.InstanceNorm1d): - x = self.norm(x.permute((0, 2, 1))).permute((0, 2, 1)) # normalize on [C] - else: - x = self.norm(x) - x = self.act(x) - return x - - -class PoseSequenceDiscriminator(nn.Module): - def __init__(self, cfg): - super().__init__() - self.cfg = cfg - leaky = self.cfg.MODEL.DISCRIMINATOR.LEAKY_RELU - - self.seq = nn.Sequential( - ConvNormRelu('1d', cfg.MODEL.DISCRIMINATOR.INPUT_CHANNELS, 256, downsample=True, leaky=leaky), # B, 256, 64 - ConvNormRelu('1d', 256, 512, downsample=True, leaky=leaky), # B, 512, 32 - ConvNormRelu('1d', 512, 1024, kernel_size=3, stride=1, padding=1, leaky=leaky), # B, 1024, 16 - nn.Conv1d(1024, 1, kernel_size=3, stride=1, padding=1, bias=True) # B, 1, 16 - ) - - def forward(self, x): - x = x.reshape(x.size(0), x.size(1), -1).transpose(1, 2) - x = self.seq(x) - x = x.squeeze(1) - return x \ No newline at end of file diff --git a/spaces/801artistry/RVC801/README.md b/spaces/801artistry/RVC801/README.md deleted file mode 100644 index 9d8914cd05791e4f8db6267eb2a5fe2133e22e58..0000000000000000000000000000000000000000 --- a/spaces/801artistry/RVC801/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: RVC Inference HF -emoji: 👀 -colorFrom: green -colorTo: green -sdk: gradio -sdk_version: 3.43.2 -app_file: app.py -pinned: false ---- \ No newline at end of file diff --git a/spaces/801artistry/RVC801/diffq/base.py b/spaces/801artistry/RVC801/diffq/base.py deleted file mode 100644 index 9bd5276b51fbed3d4b898a45b93479ff19e62a7b..0000000000000000000000000000000000000000 --- a/spaces/801artistry/RVC801/diffq/base.py +++ /dev/null @@ -1,262 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass -from concurrent import futures -from fnmatch import fnmatch -from functools import partial -import io -import math -from multiprocessing import cpu_count -import typing as tp -import zlib - -import torch - - -class BaseQuantizer: - @dataclass - class _QuantizedParam: - name: str - param: torch.nn.Parameter - module: torch.nn.Module - # If a Parameter is used multiple times, `other` can be used - # to share state between the different Quantizers - other: tp.Optional[tp.Any] - - def __init__(self, model: torch.nn.Module, min_size: float = 0.01, float16: bool = False, - exclude: tp.Optional[tp.List[str]] = [], detect_bound: bool = True): - self.model = model - self.min_size = min_size - self.float16 = float16 - self.exclude = exclude - self.detect_bound = detect_bound - self._quantized = False - self._pre_handle = self.model.register_forward_pre_hook(self._forward_pre_hook) - self._post_handle = self.model.register_forward_hook(self._forward_hook) - - self._quantized_state = None - self._qparams = [] - self._float16 = [] - self._others = [] - self._rnns = [] - - self._saved = [] - - self._find_params() - - def _find_params(self): - min_params = self.min_size * 2**20 // 4 - previous = {} - for module_name, module in self.model.named_modules(): - if isinstance(module, torch.nn.RNNBase): - self._rnns.append(module) - for name, param in list(module.named_parameters(recurse=False)): - full_name = f"{module_name}.{name}" - matched = False - for pattern in self.exclude: - if fnmatch(full_name, pattern) or fnmatch(name, pattern): - matched = True - break - - if param.numel() <= min_params or matched: - if id(param) in previous: - continue - if self.detect_bound: - previous[id(param)] = None - if self.float16: - self._float16.append(param) - else: - self._others.append(param) - else: - qparam = self._register_param(name, param, module, previous.get(id(param))) - if self.detect_bound: - previous[id(param)] = qparam - self._qparams.append(qparam) - - def _register_param(self, name, param, module, other): - return self.__class__._QuantizedParam(name, param, module, other) - - def _forward_pre_hook(self, module, input): - if self.model.training: - self._quantized_state = None - if self._quantized: - self.unquantize() - if self._pre_forward_train(): - self._fix_rnns() - else: - self.quantize() - - def _forward_hook(self, module, input, output): - if self.model.training: - if self._post_forward_train(): - self._fix_rnns(flatten=False) # Hacky, next forward will flatten - - def quantize(self, save=True): - """ - Immediately apply quantization to the model parameters. - If `save` is True, save a copy of the unquantized parameters, that can be - restored with `unquantize()`. - """ - if self._quantized: - return - if save: - self._saved = [qp.param.data.to('cpu', copy=True) - for qp in self._qparams if qp.other is None] - self.restore_quantized_state(self.get_quantized_state()) - self._quantized = True - self._fix_rnns() - - def unquantize(self): - """ - Revert a previous call to `quantize()`. - """ - if not self._quantized: - raise RuntimeError("Can only be called on a quantized model.") - if not self._saved: - raise RuntimeError("Nothing to restore.") - for qparam in self._qparams: - if qparam.other is None: - qparam.param.data[:] = self._saved.pop(0) - assert len(self._saved) == 0 - self._quantized = False - self._fix_rnns() - - def _pre_forward_train(self) -> bool: - """ - Called once before each forward for continuous quantization. - Should return True if parameters were changed. - """ - return False - - def _post_forward_train(self) -> bool: - """ - Called once after each forward (to restore state for instance). - Should return True if parameters were changed. - """ - return False - - def _fix_rnns(self, flatten=True): - """ - To be called after quantization happened to fix RNNs. - """ - for rnn in self._rnns: - rnn._flat_weights = [ - (lambda wn: getattr(rnn, wn) if hasattr(rnn, wn) else None)(wn) - for wn in rnn._flat_weights_names] - if flatten: - rnn.flatten_parameters() - - def get_quantized_state(self): - """ - Returns sufficient quantized information to rebuild the model state. - - ..Note:: - To achieve maximum compression, you should compress this with - gzip or other, as quantized weights are not optimally coded! - """ - if self._quantized_state is None: - self._quantized_state = self._get_quantized_state() - return self._quantized_state - - def _get_quantized_state(self): - """ - Actual implementation for `get_quantized_state`. - """ - float16_params = [] - for p in self._float16: - q = p.data.half() - float16_params.append(q) - - return { - "quantized": [self._quantize_param(qparam) for qparam in self._qparams - if qparam.other is None], - "float16": float16_params, - "others": [p.data.clone() for p in self._others], - } - - def _quantize_param(self, qparam: _QuantizedParam) -> tp.Any: - """ - To be overriden. - """ - raise NotImplementedError() - - def _unquantize_param(self, qparam: _QuantizedParam, quantized: tp.Any) -> torch.Tensor: - """ - To be overriden. - """ - raise NotImplementedError() - - def restore_quantized_state(self, state) -> None: - """ - Restore the state of the model from the quantized state. - """ - for p, q in zip(self._float16, state["float16"]): - p.data[:] = q.to(p) - - for p, q in zip(self._others, state["others"]): - p.data[:] = q - - remaining = list(state["quantized"]) - for qparam in self._qparams: - if qparam.other is not None: - # Only unquantize first appearance of nn.Parameter. - continue - quantized = remaining.pop(0) - qparam.param.data[:] = self._unquantize_param(qparam, quantized) - self._fix_rnns() - - def detach(self) -> None: - """ - Detach from the model, removes hooks and anything else. - """ - self._pre_handle.remove() - self._post_handle.remove() - - def model_size(self) -> torch.Tensor: - """ - Returns an estimate of the quantized model size. - """ - total = torch.tensor(0.) - for p in self._float16: - total += 16 * p.numel() - for p in self._others: - total += 32 * p.numel() - return total / 2**20 / 8 # bits to MegaBytes - - def true_model_size(self) -> float: - """ - Return the true quantized model size, in MB, without extra - compression. - """ - return self.model_size().item() - - def compressed_model_size(self, compress_level=-1, num_workers=8) -> float: - """ - Return the compressed quantized model size, in MB. - - Args: - compress_level (int): compression level used with zlib, - see `zlib.compress` for details. - num_workers (int): will split the final big byte representation in that - many chunks processed in parallels. - """ - out = io.BytesIO() - torch.save(self.get_quantized_state(), out) - ms = _parallel_compress_len(out.getvalue(), compress_level, num_workers) - return ms / 2 ** 20 - - -def _compress_len(data, compress_level): - return len(zlib.compress(data, level=compress_level)) - - -def _parallel_compress_len(data, compress_level, num_workers): - num_workers = min(cpu_count(), num_workers) - chunk_size = int(math.ceil(len(data) / num_workers)) - chunks = [data[offset:offset + chunk_size] for offset in range(0, len(data), chunk_size)] - with futures.ProcessPoolExecutor(num_workers) as pool: - return sum(pool.map(partial(_compress_len, compress_level=compress_level), chunks)) diff --git a/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/platforms/egl.py b/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/platforms/egl.py deleted file mode 100644 index ae2478d29c9a538c53ad83fa31f8e2277cd897c8..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/generate_human_motion/pyrender/pyrender/platforms/egl.py +++ /dev/null @@ -1,219 +0,0 @@ -import ctypes -import os - -import OpenGL.platform - -from .base import Platform - -EGL_PLATFORM_DEVICE_EXT = 0x313F -EGL_DRM_DEVICE_FILE_EXT = 0x3233 - - -def _ensure_egl_loaded(): - plugin = OpenGL.platform.PlatformPlugin.by_name('egl') - if plugin is None: - raise RuntimeError("EGL platform plugin is not available.") - - plugin_class = plugin.load() - plugin.loaded = True - # create instance of this platform implementation - plugin = plugin_class() - - plugin.install(vars(OpenGL.platform)) - - -_ensure_egl_loaded() -from OpenGL import EGL as egl - - -def _get_egl_func(func_name, res_type, *arg_types): - address = egl.eglGetProcAddress(func_name) - if address is None: - return None - - proto = ctypes.CFUNCTYPE(res_type) - proto.argtypes = arg_types - func = proto(address) - return func - - -def _get_egl_struct(struct_name): - from OpenGL._opaque import opaque_pointer_cls - return opaque_pointer_cls(struct_name) - - -# These are not defined in PyOpenGL by default. -_EGLDeviceEXT = _get_egl_struct('EGLDeviceEXT') -_eglGetPlatformDisplayEXT = _get_egl_func('eglGetPlatformDisplayEXT', egl.EGLDisplay) -_eglQueryDevicesEXT = _get_egl_func('eglQueryDevicesEXT', egl.EGLBoolean) -_eglQueryDeviceStringEXT = _get_egl_func('eglQueryDeviceStringEXT', ctypes.c_char_p) - - -def query_devices(): - if _eglQueryDevicesEXT is None: - raise RuntimeError("EGL query extension is not loaded or is not supported.") - - num_devices = egl.EGLint() - success = _eglQueryDevicesEXT(0, None, ctypes.pointer(num_devices)) - if not success or num_devices.value < 1: - return [] - - devices = (_EGLDeviceEXT * num_devices.value)() # array of size num_devices - success = _eglQueryDevicesEXT(num_devices.value, devices, ctypes.pointer(num_devices)) - if not success or num_devices.value < 1: - return [] - - return [EGLDevice(devices[i]) for i in range(num_devices.value)] - - -def get_default_device(): - # Fall back to not using query extension. - if _eglQueryDevicesEXT is None: - return EGLDevice(None) - - return query_devices()[0] - - -def get_device_by_index(device_id): - if _eglQueryDevicesEXT is None and device_id == 0: - return get_default_device() - - devices = query_devices() - if device_id >= len(devices): - raise ValueError('Invalid device ID ({})'.format(device_id, len(devices))) - return devices[device_id] - - -class EGLDevice: - - def __init__(self, display=None): - self._display = display - - def get_display(self): - if self._display is None: - return egl.eglGetDisplay(egl.EGL_DEFAULT_DISPLAY) - - return _eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, self._display, None) - - @property - def name(self): - if self._display is None: - return 'default' - - name = _eglQueryDeviceStringEXT(self._display, EGL_DRM_DEVICE_FILE_EXT) - if name is None: - return None - - return name.decode('ascii') - - def __repr__(self): - return "".format(self.name) - - -class EGLPlatform(Platform): - """Renders using EGL. - """ - - def __init__(self, viewport_width, viewport_height, device: EGLDevice = None): - super(EGLPlatform, self).__init__(viewport_width, viewport_height) - if device is None: - device = get_default_device() - - self._egl_device = device - self._egl_display = None - self._egl_context = None - - def init_context(self): - _ensure_egl_loaded() - - from OpenGL.EGL import ( - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_BLUE_SIZE, - EGL_RED_SIZE, EGL_GREEN_SIZE, EGL_DEPTH_SIZE, - EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_CONFORMANT, - EGL_NONE, EGL_DEFAULT_DISPLAY, EGL_NO_CONTEXT, - EGL_OPENGL_API, EGL_CONTEXT_MAJOR_VERSION, - EGL_CONTEXT_MINOR_VERSION, - EGL_CONTEXT_OPENGL_PROFILE_MASK, - EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, - eglGetDisplay, eglInitialize, eglChooseConfig, - eglBindAPI, eglCreateContext, EGLConfig - ) - from OpenGL import arrays - - config_attributes = arrays.GLintArray.asArray([ - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_BLUE_SIZE, 8, - EGL_RED_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_DEPTH_SIZE, 24, - EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, - EGL_CONFORMANT, EGL_OPENGL_BIT, - EGL_NONE - ]) - context_attributes = arrays.GLintArray.asArray([ - EGL_CONTEXT_MAJOR_VERSION, 4, - EGL_CONTEXT_MINOR_VERSION, 1, - EGL_CONTEXT_OPENGL_PROFILE_MASK, - EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, - EGL_NONE - ]) - major, minor = ctypes.c_long(), ctypes.c_long() - num_configs = ctypes.c_long() - configs = (EGLConfig * 1)() - - # Cache DISPLAY if necessary and get an off-screen EGL display - orig_dpy = None - if 'DISPLAY' in os.environ: - orig_dpy = os.environ['DISPLAY'] - del os.environ['DISPLAY'] - - self._egl_display = self._egl_device.get_display() - if orig_dpy is not None: - os.environ['DISPLAY'] = orig_dpy - - # Initialize EGL - assert eglInitialize(self._egl_display, major, minor) - assert eglChooseConfig( - self._egl_display, config_attributes, configs, 1, num_configs - ) - - # Bind EGL to the OpenGL API - assert eglBindAPI(EGL_OPENGL_API) - - # Create an EGL context - self._egl_context = eglCreateContext( - self._egl_display, configs[0], - EGL_NO_CONTEXT, context_attributes - ) - - # Make it current - self.make_current() - - def make_current(self): - from OpenGL.EGL import eglMakeCurrent, EGL_NO_SURFACE - assert eglMakeCurrent( - self._egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, - self._egl_context - ) - - def make_uncurrent(self): - """Make the OpenGL context uncurrent. - """ - pass - - def delete_context(self): - from OpenGL.EGL import eglDestroyContext, eglTerminate - if self._egl_display is not None: - if self._egl_context is not None: - eglDestroyContext(self._egl_display, self._egl_context) - self._egl_context = None - eglTerminate(self._egl_display) - self._egl_display = None - - def supports_framebuffers(self): - return True - - -__all__ = ['EGLPlatform'] diff --git a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/commons/normalizing_flow/glow_modules.py b/spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/commons/normalizing_flow/glow_modules.py deleted file mode 100644 index 1120e43133f7b76bf7ac52c120377ce57aae836c..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/commons/normalizing_flow/glow_modules.py +++ /dev/null @@ -1,362 +0,0 @@ -import scipy -from torch.nn import functional as F -import torch -from torch import nn -import numpy as np -from modules.commons.wavenet import WN -from modules.glow import utils - - -class ActNorm(nn.Module): - def __init__(self, channels, ddi=False, **kwargs): - super().__init__() - self.channels = channels - self.initialized = not ddi - - self.logs = nn.Parameter(torch.zeros(1, channels, 1)) - self.bias = nn.Parameter(torch.zeros(1, channels, 1)) - - def forward(self, x, x_mask=None, reverse=False, **kwargs): - if x_mask is None: - x_mask = torch.ones(x.size(0), 1, x.size(2)).to(device=x.device, dtype=x.dtype) - x_len = torch.sum(x_mask, [1, 2]) - if not self.initialized: - self.initialize(x, x_mask) - self.initialized = True - - if reverse: - z = (x - self.bias) * torch.exp(-self.logs) * x_mask - logdet = torch.sum(-self.logs) * x_len - else: - z = (self.bias + torch.exp(self.logs) * x) * x_mask - logdet = torch.sum(self.logs) * x_len # [b] - return z, logdet - - def store_inverse(self): - pass - - def set_ddi(self, ddi): - self.initialized = not ddi - - def initialize(self, x, x_mask): - with torch.no_grad(): - denom = torch.sum(x_mask, [0, 2]) - m = torch.sum(x * x_mask, [0, 2]) / denom - m_sq = torch.sum(x * x * x_mask, [0, 2]) / denom - v = m_sq - (m ** 2) - logs = 0.5 * torch.log(torch.clamp_min(v, 1e-6)) - - bias_init = (-m * torch.exp(-logs)).view(*self.bias.shape).to(dtype=self.bias.dtype) - logs_init = (-logs).view(*self.logs.shape).to(dtype=self.logs.dtype) - - self.bias.data.copy_(bias_init) - self.logs.data.copy_(logs_init) - - -class InvConvNear(nn.Module): - def __init__(self, channels, n_split=4, no_jacobian=False, lu=True, n_sqz=2, **kwargs): - super().__init__() - assert (n_split % 2 == 0) - self.channels = channels - self.n_split = n_split - self.n_sqz = n_sqz - self.no_jacobian = no_jacobian - - w_init = torch.qr(torch.FloatTensor(self.n_split, self.n_split).normal_())[0] - if torch.det(w_init) < 0: - w_init[:, 0] = -1 * w_init[:, 0] - self.lu = lu - if lu: - # LU decomposition can slightly speed up the inverse - np_p, np_l, np_u = scipy.linalg.lu(w_init) - np_s = np.diag(np_u) - np_sign_s = np.sign(np_s) - np_log_s = np.log(np.abs(np_s)) - np_u = np.triu(np_u, k=1) - l_mask = np.tril(np.ones(w_init.shape, dtype=float), -1) - eye = np.eye(*w_init.shape, dtype=float) - - self.register_buffer('p', torch.Tensor(np_p.astype(float))) - self.register_buffer('sign_s', torch.Tensor(np_sign_s.astype(float))) - self.l = nn.Parameter(torch.Tensor(np_l.astype(float)), requires_grad=True) - self.log_s = nn.Parameter(torch.Tensor(np_log_s.astype(float)), requires_grad=True) - self.u = nn.Parameter(torch.Tensor(np_u.astype(float)), requires_grad=True) - self.register_buffer('l_mask', torch.Tensor(l_mask)) - self.register_buffer('eye', torch.Tensor(eye)) - else: - self.weight = nn.Parameter(w_init) - - def forward(self, x, x_mask=None, reverse=False, **kwargs): - b, c, t = x.size() - assert (c % self.n_split == 0) - if x_mask is None: - x_mask = 1 - x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t - else: - x_len = torch.sum(x_mask, [1, 2]) - - x = x.view(b, self.n_sqz, c // self.n_split, self.n_split // self.n_sqz, t) - x = x.permute(0, 1, 3, 2, 4).contiguous().view(b, self.n_split, c // self.n_split, t) - - if self.lu: - self.weight, log_s = self._get_weight() - logdet = log_s.sum() - logdet = logdet * (c / self.n_split) * x_len - else: - logdet = torch.logdet(self.weight) * (c / self.n_split) * x_len # [b] - - if reverse: - if hasattr(self, "weight_inv"): - weight = self.weight_inv - else: - weight = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype) - logdet = -logdet - else: - weight = self.weight - if self.no_jacobian: - logdet = 0 - - weight = weight.view(self.n_split, self.n_split, 1, 1) - z = F.conv2d(x, weight) - - z = z.view(b, self.n_sqz, self.n_split // self.n_sqz, c // self.n_split, t) - z = z.permute(0, 1, 3, 2, 4).contiguous().view(b, c, t) * x_mask - return z, logdet - - def _get_weight(self): - l, log_s, u = self.l, self.log_s, self.u - l = l * self.l_mask + self.eye - u = u * self.l_mask.transpose(0, 1).contiguous() + torch.diag(self.sign_s * torch.exp(log_s)) - weight = torch.matmul(self.p, torch.matmul(l, u)) - return weight, log_s - - def store_inverse(self): - weight, _ = self._get_weight() - self.weight_inv = torch.inverse(weight.float()).to(next(self.parameters()).device) - - -class InvConv(nn.Module): - def __init__(self, channels, no_jacobian=False, lu=True, **kwargs): - super().__init__() - w_shape = [channels, channels] - w_init = np.linalg.qr(np.random.randn(*w_shape))[0].astype(float) - LU_decomposed = lu - if not LU_decomposed: - # Sample a random orthogonal matrix: - self.register_parameter("weight", nn.Parameter(torch.Tensor(w_init))) - else: - np_p, np_l, np_u = scipy.linalg.lu(w_init) - np_s = np.diag(np_u) - np_sign_s = np.sign(np_s) - np_log_s = np.log(np.abs(np_s)) - np_u = np.triu(np_u, k=1) - l_mask = np.tril(np.ones(w_shape, dtype=float), -1) - eye = np.eye(*w_shape, dtype=float) - - self.register_buffer('p', torch.Tensor(np_p.astype(float))) - self.register_buffer('sign_s', torch.Tensor(np_sign_s.astype(float))) - self.l = nn.Parameter(torch.Tensor(np_l.astype(float))) - self.log_s = nn.Parameter(torch.Tensor(np_log_s.astype(float))) - self.u = nn.Parameter(torch.Tensor(np_u.astype(float))) - self.l_mask = torch.Tensor(l_mask) - self.eye = torch.Tensor(eye) - self.w_shape = w_shape - self.LU = LU_decomposed - self.weight = None - - def get_weight(self, device, reverse): - w_shape = self.w_shape - self.p = self.p.to(device) - self.sign_s = self.sign_s.to(device) - self.l_mask = self.l_mask.to(device) - self.eye = self.eye.to(device) - l = self.l * self.l_mask + self.eye - u = self.u * self.l_mask.transpose(0, 1).contiguous() + torch.diag(self.sign_s * torch.exp(self.log_s)) - dlogdet = self.log_s.sum() - if not reverse: - w = torch.matmul(self.p, torch.matmul(l, u)) - else: - l = torch.inverse(l.double()).float() - u = torch.inverse(u.double()).float() - w = torch.matmul(u, torch.matmul(l, self.p.inverse())) - return w.view(w_shape[0], w_shape[1], 1), dlogdet - - def forward(self, x, x_mask=None, reverse=False, **kwargs): - """ - log-det = log|abs(|W|)| * pixels - """ - b, c, t = x.size() - if x_mask is None: - x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t - else: - x_len = torch.sum(x_mask, [1, 2]) - logdet = 0 - if not reverse: - weight, dlogdet = self.get_weight(x.device, reverse) - z = F.conv1d(x, weight) - if logdet is not None: - logdet = logdet + dlogdet * x_len - return z, logdet - else: - if self.weight is None: - weight, dlogdet = self.get_weight(x.device, reverse) - else: - weight, dlogdet = self.weight, self.dlogdet - z = F.conv1d(x, weight) - if logdet is not None: - logdet = logdet - dlogdet * x_len - return z, logdet - - def store_inverse(self): - self.weight, self.dlogdet = self.get_weight('cuda', reverse=True) - - -class CouplingBlock(nn.Module): - def __init__(self, in_channels, hidden_channels, kernel_size, dilation_rate, n_layers, - gin_channels=0, p_dropout=0, sigmoid_scale=False, wn=None): - super().__init__() - self.in_channels = in_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.p_dropout = p_dropout - self.sigmoid_scale = sigmoid_scale - - start = torch.nn.Conv1d(in_channels // 2, hidden_channels, 1) - start = torch.nn.utils.weight_norm(start) - self.start = start - # Initializing last layer to 0 makes the affine coupling layers - # do nothing at first. This helps with training stability - end = torch.nn.Conv1d(hidden_channels, in_channels, 1) - end.weight.data.zero_() - end.bias.data.zero_() - self.end = end - self.wn = WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels, p_dropout) - if wn is not None: - self.wn.in_layers = wn.in_layers - self.wn.res_skip_layers = wn.res_skip_layers - - def forward(self, x, x_mask=None, reverse=False, g=None, **kwargs): - if x_mask is None: - x_mask = 1 - x_0, x_1 = x[:, :self.in_channels // 2], x[:, self.in_channels // 2:] - - x = self.start(x_0) * x_mask - x = self.wn(x, x_mask, g) - out = self.end(x) - - z_0 = x_0 - m = out[:, :self.in_channels // 2, :] - logs = out[:, self.in_channels // 2:, :] - if self.sigmoid_scale: - logs = torch.log(1e-6 + torch.sigmoid(logs + 2)) - if reverse: - z_1 = (x_1 - m) * torch.exp(-logs) * x_mask - logdet = torch.sum(-logs * x_mask, [1, 2]) - else: - z_1 = (m + torch.exp(logs) * x_1) * x_mask - logdet = torch.sum(logs * x_mask, [1, 2]) - z = torch.cat([z_0, z_1], 1) - return z, logdet - - def store_inverse(self): - self.wn.remove_weight_norm() - - -class Glow(nn.Module): - def __init__(self, - in_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_blocks, - n_layers, - p_dropout=0., - n_split=4, - n_sqz=2, - sigmoid_scale=False, - gin_channels=0, - inv_conv_type='near', - share_cond_layers=False, - share_wn_layers=0, - ): - super().__init__() - - self.in_channels = in_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_blocks = n_blocks - self.n_layers = n_layers - self.p_dropout = p_dropout - self.n_split = n_split - self.n_sqz = n_sqz - self.sigmoid_scale = sigmoid_scale - self.gin_channels = gin_channels - self.share_cond_layers = share_cond_layers - if gin_channels != 0 and share_cond_layers: - cond_layer = torch.nn.Conv1d(gin_channels * n_sqz, 2 * hidden_channels * n_layers, 1) - self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight') - wn = None - self.flows = nn.ModuleList() - for b in range(n_blocks): - self.flows.append(ActNorm(channels=in_channels * n_sqz)) - if inv_conv_type == 'near': - self.flows.append(InvConvNear(channels=in_channels * n_sqz, n_split=n_split, n_sqz=n_sqz)) - if inv_conv_type == 'invconv': - self.flows.append(InvConv(channels=in_channels * n_sqz)) - if share_wn_layers > 0: - if b % share_wn_layers == 0: - wn = WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels * n_sqz, - p_dropout, share_cond_layers) - self.flows.append( - CouplingBlock( - in_channels * n_sqz, - hidden_channels, - kernel_size=kernel_size, - dilation_rate=dilation_rate, - n_layers=n_layers, - gin_channels=gin_channels * n_sqz, - p_dropout=p_dropout, - sigmoid_scale=sigmoid_scale, - wn=wn - )) - - def forward(self, x, x_mask=None, g=None, reverse=False, return_hiddens=False): - logdet_tot = 0 - if not reverse: - flows = self.flows - else: - flows = reversed(self.flows) - if return_hiddens: - hs = [] - if self.n_sqz > 1: - x, x_mask_ = utils.squeeze(x, x_mask, self.n_sqz) - if g is not None: - g, _ = utils.squeeze(g, x_mask, self.n_sqz) - x_mask = x_mask_ - if self.share_cond_layers and g is not None: - g = self.cond_layer(g) - for f in flows: - x, logdet = f(x, x_mask, g=g, reverse=reverse) - if return_hiddens: - hs.append(x) - logdet_tot += logdet - if self.n_sqz > 1: - x, x_mask = utils.unsqueeze(x, x_mask, self.n_sqz) - if return_hiddens: - return x, logdet_tot, hs - return x, logdet_tot - - def store_inverse(self): - def remove_weight_norm(m): - try: - nn.utils.remove_weight_norm(m) - except ValueError: # this module didn't have weight norm - return - - self.apply(remove_weight_norm) - for f in self.flows: - f.store_inverse() diff --git a/spaces/AIGC-Audio/Make_An_Audio_inpaint/ldm/modules/x_transformer.py b/spaces/AIGC-Audio/Make_An_Audio_inpaint/ldm/modules/x_transformer.py deleted file mode 100644 index 5fc15bf9cfe0111a910e7de33d04ffdec3877576..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/Make_An_Audio_inpaint/ldm/modules/x_transformer.py +++ /dev/null @@ -1,641 +0,0 @@ -"""shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers""" -import torch -from torch import nn, einsum -import torch.nn.functional as F -from functools import partial -from inspect import isfunction -from collections import namedtuple -from einops import rearrange, repeat, reduce - -# constants - -DEFAULT_DIM_HEAD = 64 - -Intermediates = namedtuple('Intermediates', [ - 'pre_softmax_attn', - 'post_softmax_attn' -]) - -LayerIntermediates = namedtuple('Intermediates', [ - 'hiddens', - 'attn_intermediates' -]) - - -class AbsolutePositionalEmbedding(nn.Module): - def __init__(self, dim, max_seq_len): - super().__init__() - self.emb = nn.Embedding(max_seq_len, dim) - self.init_() - - def init_(self): - nn.init.normal_(self.emb.weight, std=0.02) - - def forward(self, x): - n = torch.arange(x.shape[1], device=x.device) - return self.emb(n)[None, :, :] - - -class FixedPositionalEmbedding(nn.Module): - def __init__(self, dim): - super().__init__() - inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) - self.register_buffer('inv_freq', inv_freq) - - def forward(self, x, seq_dim=1, offset=0): - t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset - sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq) - emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) - return emb[None, :, :] - - -# helpers - -def exists(val): - return val is not None - - -def default(val, d): - if exists(val): - return val - return d() if isfunction(d) else d - - -def always(val): - def inner(*args, **kwargs): - return val - return inner - - -def not_equals(val): - def inner(x): - return x != val - return inner - - -def equals(val): - def inner(x): - return x == val - return inner - - -def max_neg_value(tensor): - return -torch.finfo(tensor.dtype).max - - -# keyword argument helpers - -def pick_and_pop(keys, d): - values = list(map(lambda key: d.pop(key), keys)) - return dict(zip(keys, values)) - - -def group_dict_by_key(cond, d): - return_val = [dict(), dict()] - for key in d.keys(): - match = bool(cond(key)) - ind = int(not match) - return_val[ind][key] = d[key] - return (*return_val,) - - -def string_begins_with(prefix, str): - return str.startswith(prefix) - - -def group_by_key_prefix(prefix, d): - return group_dict_by_key(partial(string_begins_with, prefix), d) - - -def groupby_prefix_and_trim(prefix, d): - kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d) - kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items()))) - return kwargs_without_prefix, kwargs - - -# classes -class Scale(nn.Module): - def __init__(self, value, fn): - super().__init__() - self.value = value - self.fn = fn - - def forward(self, x, **kwargs): - x, *rest = self.fn(x, **kwargs) - return (x * self.value, *rest) - - -class Rezero(nn.Module): - def __init__(self, fn): - super().__init__() - self.fn = fn - self.g = nn.Parameter(torch.zeros(1)) - - def forward(self, x, **kwargs): - x, *rest = self.fn(x, **kwargs) - return (x * self.g, *rest) - - -class ScaleNorm(nn.Module): - def __init__(self, dim, eps=1e-5): - super().__init__() - self.scale = dim ** -0.5 - self.eps = eps - self.g = nn.Parameter(torch.ones(1)) - - def forward(self, x): - norm = torch.norm(x, dim=-1, keepdim=True) * self.scale - return x / norm.clamp(min=self.eps) * self.g - - -class RMSNorm(nn.Module): - def __init__(self, dim, eps=1e-8): - super().__init__() - self.scale = dim ** -0.5 - self.eps = eps - self.g = nn.Parameter(torch.ones(dim)) - - def forward(self, x): - norm = torch.norm(x, dim=-1, keepdim=True) * self.scale - return x / norm.clamp(min=self.eps) * self.g - - -class Residual(nn.Module): - def forward(self, x, residual): - return x + residual - - -class GRUGating(nn.Module): - def __init__(self, dim): - super().__init__() - self.gru = nn.GRUCell(dim, dim) - - def forward(self, x, residual): - gated_output = self.gru( - rearrange(x, 'b n d -> (b n) d'), - rearrange(residual, 'b n d -> (b n) d') - ) - - return gated_output.reshape_as(x) - - -# feedforward - -class GEGLU(nn.Module): - def __init__(self, dim_in, dim_out): - super().__init__() - self.proj = nn.Linear(dim_in, dim_out * 2) - - def forward(self, x): - x, gate = self.proj(x).chunk(2, dim=-1) - return x * F.gelu(gate) - - -class FeedForward(nn.Module): - def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.): - super().__init__() - inner_dim = int(dim * mult) - dim_out = default(dim_out, dim) - project_in = nn.Sequential( - nn.Linear(dim, inner_dim), - nn.GELU() - ) if not glu else GEGLU(dim, inner_dim) - - self.net = nn.Sequential( - project_in, - nn.Dropout(dropout), - nn.Linear(inner_dim, dim_out) - ) - - def forward(self, x): - return self.net(x) - - -# attention. -class Attention(nn.Module): - def __init__( - self, - dim, - dim_head=DEFAULT_DIM_HEAD, - heads=8, - causal=False, - mask=None, - talking_heads=False, - sparse_topk=None, - use_entmax15=False, - num_mem_kv=0, - dropout=0., - on_attn=False - ): - super().__init__() - if use_entmax15: - raise NotImplementedError("Check out entmax activation instead of softmax activation!") - self.scale = dim_head ** -0.5 - self.heads = heads - self.causal = causal - self.mask = mask - - inner_dim = dim_head * heads - - self.to_q = nn.Linear(dim, inner_dim, bias=False) - self.to_k = nn.Linear(dim, inner_dim, bias=False) - self.to_v = nn.Linear(dim, inner_dim, bias=False) - self.dropout = nn.Dropout(dropout) - - # talking heads - self.talking_heads = talking_heads - if talking_heads: - self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads)) - self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads)) - - # explicit topk sparse attention - self.sparse_topk = sparse_topk - - # entmax - #self.attn_fn = entmax15 if use_entmax15 else F.softmax - self.attn_fn = F.softmax - - # add memory key / values - self.num_mem_kv = num_mem_kv - if num_mem_kv > 0: - self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) - self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) - - # attention on attention - self.attn_on_attn = on_attn - self.to_out = nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(inner_dim, dim) - - def forward( - self, - x, - context=None, - mask=None, - context_mask=None, - rel_pos=None, - sinusoidal_emb=None, - prev_attn=None, - mem=None - ): - b, n, _, h, talking_heads, device = *x.shape, self.heads, self.talking_heads, x.device - kv_input = default(context, x) - - q_input = x - k_input = kv_input - v_input = kv_input - - if exists(mem): - k_input = torch.cat((mem, k_input), dim=-2) - v_input = torch.cat((mem, v_input), dim=-2) - - if exists(sinusoidal_emb): - # in shortformer, the query would start at a position offset depending on the past cached memory - offset = k_input.shape[-2] - q_input.shape[-2] - q_input = q_input + sinusoidal_emb(q_input, offset=offset) - k_input = k_input + sinusoidal_emb(k_input) - - q = self.to_q(q_input) - k = self.to_k(k_input) - v = self.to_v(v_input) - - q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v)) - - input_mask = None - if any(map(exists, (mask, context_mask))): - q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool()) - k_mask = q_mask if not exists(context) else context_mask - k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool()) - q_mask = rearrange(q_mask, 'b i -> b () i ()') - k_mask = rearrange(k_mask, 'b j -> b () () j') - input_mask = q_mask * k_mask - - if self.num_mem_kv > 0: - mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v)) - k = torch.cat((mem_k, k), dim=-2) - v = torch.cat((mem_v, v), dim=-2) - if exists(input_mask): - input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True) - - dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale - mask_value = max_neg_value(dots) - - if exists(prev_attn): - dots = dots + prev_attn - - pre_softmax_attn = dots - - if talking_heads: - dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous() - - if exists(rel_pos): - dots = rel_pos(dots) - - if exists(input_mask): - dots.masked_fill_(~input_mask, mask_value) - del input_mask - - if self.causal: - i, j = dots.shape[-2:] - r = torch.arange(i, device=device) - mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j') - mask = F.pad(mask, (j - i, 0), value=False) - dots.masked_fill_(mask, mask_value) - del mask - - if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]: - top, _ = dots.topk(self.sparse_topk, dim=-1) - vk = top[..., -1].unsqueeze(-1).expand_as(dots) - mask = dots < vk - dots.masked_fill_(mask, mask_value) - del mask - - attn = self.attn_fn(dots, dim=-1) - post_softmax_attn = attn - - attn = self.dropout(attn) - - if talking_heads: - attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous() - - out = einsum('b h i j, b h j d -> b h i d', attn, v) - out = rearrange(out, 'b h n d -> b n (h d)') - - intermediates = Intermediates( - pre_softmax_attn=pre_softmax_attn, - post_softmax_attn=post_softmax_attn - ) - - return self.to_out(out), intermediates - - -class AttentionLayers(nn.Module): - def __init__( - self, - dim, - depth, - heads=8, - causal=False, - cross_attend=False, - only_cross=False, - use_scalenorm=False, - use_rmsnorm=False, - use_rezero=False, - rel_pos_num_buckets=32, - rel_pos_max_distance=128, - position_infused_attn=False, - custom_layers=None, - sandwich_coef=None, - par_ratio=None, - residual_attn=False, - cross_residual_attn=False, - macaron=False, - pre_norm=True, - gate_residual=False, - **kwargs - ): - super().__init__() - ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs) - attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs) - - dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD) - - self.dim = dim - self.depth = depth - self.layers = nn.ModuleList([]) - - self.has_pos_emb = position_infused_attn - self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None - self.rotary_pos_emb = always(None) - - assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance' - self.rel_pos = None - - self.pre_norm = pre_norm - - self.residual_attn = residual_attn - self.cross_residual_attn = cross_residual_attn - - norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm - norm_class = RMSNorm if use_rmsnorm else norm_class - norm_fn = partial(norm_class, dim) - - norm_fn = nn.Identity if use_rezero else norm_fn - branch_fn = Rezero if use_rezero else None - - if cross_attend and not only_cross: - default_block = ('a', 'c', 'f') - elif cross_attend and only_cross: - default_block = ('c', 'f') - else: - default_block = ('a', 'f') - - if macaron: - default_block = ('f',) + default_block - - if exists(custom_layers): - layer_types = custom_layers - elif exists(par_ratio): - par_depth = depth * len(default_block) - assert 1 < par_ratio <= par_depth, 'par ratio out of range' - default_block = tuple(filter(not_equals('f'), default_block)) - par_attn = par_depth // par_ratio - depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper - par_width = (depth_cut + depth_cut // par_attn) // par_attn - assert len(default_block) <= par_width, 'default block is too large for par_ratio' - par_block = default_block + ('f',) * (par_width - len(default_block)) - par_head = par_block * par_attn - layer_types = par_head + ('f',) * (par_depth - len(par_head)) - elif exists(sandwich_coef): - assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth' - layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef - else: - layer_types = default_block * depth - - self.layer_types = layer_types - self.num_attn_layers = len(list(filter(equals('a'), layer_types))) - - for layer_type in self.layer_types: - if layer_type == 'a': - layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs) - elif layer_type == 'c': - layer = Attention(dim, heads=heads, **attn_kwargs) - elif layer_type == 'f': - layer = FeedForward(dim, **ff_kwargs) - layer = layer if not macaron else Scale(0.5, layer) - else: - raise Exception(f'invalid layer type {layer_type}') - - if isinstance(layer, Attention) and exists(branch_fn): - layer = branch_fn(layer) - - if gate_residual: - residual_fn = GRUGating(dim) - else: - residual_fn = Residual() - - self.layers.append(nn.ModuleList([ - norm_fn(), - layer, - residual_fn - ])) - - def forward( - self, - x, - context=None, - mask=None, - context_mask=None, - mems=None, - return_hiddens=False - ): - hiddens = [] - intermediates = [] - prev_attn = None - prev_cross_attn = None - - mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers - - for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)): - is_last = ind == (len(self.layers) - 1) - - if layer_type == 'a': - hiddens.append(x) - layer_mem = mems.pop(0) - - residual = x - - if self.pre_norm: - x = norm(x) - - if layer_type == 'a': - out, inter = block(x, mask=mask, sinusoidal_emb=self.pia_pos_emb, rel_pos=self.rel_pos, - prev_attn=prev_attn, mem=layer_mem) - elif layer_type == 'c': - out, inter = block(x, context=context, mask=mask, context_mask=context_mask, prev_attn=prev_cross_attn) - elif layer_type == 'f': - out = block(x) - - x = residual_fn(out, residual) - - if layer_type in ('a', 'c'): - intermediates.append(inter) - - if layer_type == 'a' and self.residual_attn: - prev_attn = inter.pre_softmax_attn - elif layer_type == 'c' and self.cross_residual_attn: - prev_cross_attn = inter.pre_softmax_attn - - if not self.pre_norm and not is_last: - x = norm(x) - - if return_hiddens: - intermediates = LayerIntermediates( - hiddens=hiddens, - attn_intermediates=intermediates - ) - - return x, intermediates - - return x - - -class Encoder(AttentionLayers): - def __init__(self, **kwargs): - assert 'causal' not in kwargs, 'cannot set causality on encoder' - super().__init__(causal=False, **kwargs) - - - -class TransformerWrapper(nn.Module): - def __init__( - self, - *, - num_tokens, - max_seq_len, - attn_layers, - emb_dim=None, - max_mem_len=0., - emb_dropout=0., - num_memory_tokens=None, - tie_embedding=False, - use_pos_emb=True - ): - super().__init__() - assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder' - - dim = attn_layers.dim - emb_dim = default(emb_dim, dim) - - self.max_seq_len = max_seq_len - self.max_mem_len = max_mem_len - self.num_tokens = num_tokens - - self.token_emb = nn.Embedding(num_tokens, emb_dim) - self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if ( - use_pos_emb and not attn_layers.has_pos_emb) else always(0) - self.emb_dropout = nn.Dropout(emb_dropout) - - self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity() - self.attn_layers = attn_layers - self.norm = nn.LayerNorm(dim) - - self.init_() - - self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t() - - # memory tokens (like [cls]) from Memory Transformers paper - num_memory_tokens = default(num_memory_tokens, 0) - self.num_memory_tokens = num_memory_tokens - if num_memory_tokens > 0: - self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim)) - - # let funnel encoder know number of memory tokens, if specified - if hasattr(attn_layers, 'num_memory_tokens'): - attn_layers.num_memory_tokens = num_memory_tokens - - def init_(self): - nn.init.normal_(self.token_emb.weight, std=0.02) - - def forward( - self, - x, - return_embeddings=False, - mask=None, - return_mems=False, - return_attn=False, - mems=None, - **kwargs - ): - b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens - x = self.token_emb(x) - x += self.pos_emb(x) - x = self.emb_dropout(x) - - x = self.project_emb(x) - - if num_mem > 0: - mem = repeat(self.memory_tokens, 'n d -> b n d', b=b) - x = torch.cat((mem, x), dim=1) - - # auto-handle masking after appending memory tokens - if exists(mask): - mask = F.pad(mask, (num_mem, 0), value=True) - - x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs) - x = self.norm(x) - - mem, x = x[:, :num_mem], x[:, num_mem:] - - out = self.to_logits(x) if not return_embeddings else x - - if return_mems: - hiddens = intermediates.hiddens - new_mems = list(map(lambda pair: torch.cat(pair, dim=-2), zip(mems, hiddens))) if exists(mems) else hiddens - new_mems = list(map(lambda t: t[..., -self.max_mem_len:, :].detach(), new_mems)) - return out, new_mems - - if return_attn: - attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates)) - return out, attn_maps - - return out - diff --git a/spaces/AIGText/GlyphControl/annotator/util.py b/spaces/AIGText/GlyphControl/annotator/util.py deleted file mode 100644 index 90831643d19cc1b9b0940df3d4fd4d846ba74a05..0000000000000000000000000000000000000000 --- a/spaces/AIGText/GlyphControl/annotator/util.py +++ /dev/null @@ -1,38 +0,0 @@ -import numpy as np -import cv2 -import os - - -annotator_ckpts_path = os.path.join(os.path.dirname(__file__), 'ckpts') - - -def HWC3(x): - assert x.dtype == np.uint8 - if x.ndim == 2: - x = x[:, :, None] - assert x.ndim == 3 - H, W, C = x.shape - assert C == 1 or C == 3 or C == 4 - if C == 3: - return x - if C == 1: - return np.concatenate([x, x, x], axis=2) - if C == 4: - color = x[:, :, 0:3].astype(np.float32) - alpha = x[:, :, 3:4].astype(np.float32) / 255.0 - y = color * alpha + 255.0 * (1.0 - alpha) - y = y.clip(0, 255).astype(np.uint8) - return y - - -def resize_image(input_image, resolution): - H, W, C = input_image.shape - H = float(H) - W = float(W) - k = float(resolution) / min(H, W) - H *= k - W *= k - H = int(np.round(H / 64.0)) * 64 - W = int(np.round(W / 64.0)) * 64 - img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA) - return img diff --git a/spaces/AIatUIUC/CodeLATS/executors/executor_types.py b/spaces/AIatUIUC/CodeLATS/executors/executor_types.py deleted file mode 100644 index 5e3e95c528400b1b5d90e4c678a7b68ddde82311..0000000000000000000000000000000000000000 --- a/spaces/AIatUIUC/CodeLATS/executors/executor_types.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import NamedTuple, List, Tuple -from abc import ABC, abstractmethod - -class ExecuteResult(NamedTuple): - is_passing: bool - feedback: str - state: Tuple[bool] - -class Executor(ABC): - @abstractmethod - def execute(self, func: str, tests: List[str], timeout: int = 5) -> ExecuteResult: - ... - - @abstractmethod - def evaluate(self, name: str, func: str, test: str, timeout: int = 5) -> bool: - ... - - - - diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov5/crowdhuman/yolov5_s-v61_fast_8xb16-300e_crowdhuman.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov5/crowdhuman/yolov5_s-v61_fast_8xb16-300e_crowdhuman.py deleted file mode 100644 index a61859fa0f2c0ea8a08ffd7783adc4ccac8540dd..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov5/crowdhuman/yolov5_s-v61_fast_8xb16-300e_crowdhuman.py +++ /dev/null @@ -1,47 +0,0 @@ -_base_ = '../yolov5_s-v61_syncbn_fast_8xb16-300e_coco.py' - -# Use the model trained on the COCO as the pretrained model -load_from = 'https://download.openmmlab.com/mmyolo/v0/yolov5/yolov5_s-v61_syncbn_fast_8xb16-300e_coco/yolov5_s-v61_syncbn_fast_8xb16-300e_coco_20220918_084700-86e02187.pth' # noqa - -# dataset settings -data_root = 'data/CrowdHuman/' -dataset_type = 'YOLOv5CrowdHumanDataset' - -# parameters that often need to be modified -num_classes = 1 - -anchors = [ - [(6, 14), (12, 28), (19, 48)], # P3/8 - [(29, 79), (46, 124), (142, 54)], # P4/16 - [(73, 198), (124, 330), (255, 504)] # P5/32 -] - -model = dict( - bbox_head=dict( - head_module=dict(num_classes=num_classes), - prior_generator=dict(base_sizes=anchors))) - -train_dataloader = dict( - dataset=dict( - type=dataset_type, - data_root=data_root, - ann_file='annotation_train.odgt', - data_prefix=dict(img='Images/'))) - -val_dataloader = dict( - dataset=dict( - type=dataset_type, - data_root=data_root, - ann_file='annotation_val.odgt', - data_prefix=dict(img='Images/'), - # CrowdHumanMetric does not support out-of-order output images - # for the time being. batch_shapes_cfg does not support. - batch_shapes_cfg=None)) -test_dataloader = val_dataloader - -val_evaluator = dict( - _delete_=True, - type='mmdet.CrowdHumanMetric', - ann_file=data_root + 'annotation_val.odgt', - metric=['AP', 'MR', 'JI']) -test_evaluator = val_evaluator diff --git a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/selector/classroom.py b/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/selector/classroom.py deleted file mode 100644 index 07365b2792b9edfda61d238bd5d3155108b954b3..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/selector/classroom.py +++ /dev/null @@ -1,47 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, List - -from agentverse.message import Message - -from . import selector_registry as SelectorRegistry -from .base import BaseSelector - -if TYPE_CHECKING: - from agentverse.environments import BaseEnvironment - - -@SelectorRegistry.register("classroom") -class ClassroomSelector(BaseSelector): - def select_message( - self, environment: BaseEnvironment, messages: List[Message] - ) -> List[Message]: - selected = [] - for message in messages: - if message.sender.startswith("Student"): - if message.content.startswith("[RaiseHand]"): - message.content = "[RaiseHand]" - selected.append(message) - elif message.content != "" or len(message.tool_response) > 0: - selected.append(message) - elif message.sender.startswith("Professor"): - # If the professor launch a group discussion, then we - # brutely discard the student's message in this turn - if message.content.startswith("[GroupDiscuss]"): - return [message] - selected.append(message) - - # If some student speak while the professor is speaking, then - # we brutely discard the student's message in this turn - if ( - len(selected) > 1 - and selected[0].sender.startswith("Professor") - and selected[0].content != "" - ): - filtered_selected = [] - filtered_selected.append(selected[0]) - for message in selected[1:]: - if message.content.startswith("[RaiseHand]"): - filtered_selected.append(message) - selected = filtered_selected - return selected diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Custom.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Custom.js deleted file mode 100644 index c872b93303aa9ecaf56517b44c38cd587d23c26c..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/custom/Custom.js +++ /dev/null @@ -1,18 +0,0 @@ -import Base from '../base/Base.js'; -import ShapesUpdateMethods from '../../../plugins/gameobjects/shape/customshapes/ShapesUpdateMethods.js'; - -const GetValue = Phaser.Utils.Objects.GetValue; - -class Custom extends Base { - constructor(scene, config) { - super(scene, config); - this.type = GetValue(config, 'type', 'rexSpinnerCustom'); - } -} - -Object.assign( - Custom.prototype, - ShapesUpdateMethods -); - -export default Custom; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/gridtable/input/SwipeCell.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/gridtable/input/SwipeCell.js deleted file mode 100644 index 673107d20d4df61ad6a0442d9c5baf517cab21dd..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/gridtable/input/SwipeCell.js +++ /dev/null @@ -1,26 +0,0 @@ -import Swipe from '../../swipe/Swipe.js'; -import EmitCellEvent from './EmitCellEvent.js'; - -const GetValue = Phaser.Utils.Objects.GetValue; - -var SwipeCell = function (table, tableConfig) { - var swipeConfig = GetValue(tableConfig, 'swipe', undefined); - if (swipeConfig === false) { - return; - } else if (swipeConfig === undefined) { - swipeConfig = {}; - } - swipeConfig.dir = '4dir'; - table._swipe = new Swipe(table, swipeConfig); - table._swipe - .on('swipe', function (swipe, gameObject, lastPointer) { - var dirName = - (swipe.left) ? 'left' : - (swipe.right) ? 'right' : - (swipe.up) ? 'up' : - 'down'; - EmitCellEvent(this.eventEmitter, `cell.swipe${dirName}`, table, swipe.worldX, swipe.worldY, lastPointer); - }, this) -}; - -export default SwipeCell; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/sides/Sides.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/sides/Sides.js deleted file mode 100644 index 96de4671f03abe3c1efb3da4e0a2a7f421f5a8f5..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/sides/Sides.js +++ /dev/null @@ -1,84 +0,0 @@ -import OverlapSizer from '../overlapsizer/OverlapSizer.js'; -import IsFunction from '../../../plugins/utils/object/IsFunction.js'; -import GetDefaultCallbacks from './defaultcallbacks/GetDefaultCallbacks.js'; -import ShowChildMethods from './ShowChildMethods.js'; -import ChildBehaviorMethods from './childbehaviors/index.js'; - -const GetValue = Phaser.Utils.Objects.GetValue; - -class Sides extends OverlapSizer { - constructor(scene, config) { - super(scene, config); - this.type = 'rexSides'; - this.childrenMap = this.sizerChildren; - this.previousChildKey = undefined; - this.currentChildKey = undefined; - - // Callbacks - var showChildCallback = GetValue(config, 'showChildCallback', undefined); - if (showChildCallback) { // Has showChildCallback, and hideChildCallback - if (IsFunction(showChildCallback)) { // Custom callbacks - var showChildCallbackScope = GetValue(config, 'showChildCallbackScope', undefined); - this.on('showchild', showChildCallback, showChildCallbackScope); - - var hideChildCallback = GetValue(config, 'hideChildCallback', undefined); - var hideChildCallbackScope = GetValue(config, 'hideChildCallbackScope', undefined); - this.on('hidechild', hideChildCallback, hideChildCallbackScope); - } else { // Default callbacks - var defaultCallbacks = GetDefaultCallbacks(showChildCallback); - this.on('showchild', defaultCallbacks.show); - this.on('hidechild', defaultCallbacks.hide); - } - } - - // Add elements - var background = GetValue(config, 'background', undefined); - var panel = GetValue(config, 'panel', undefined); - var leftSide = GetValue(config, 'leftSide', undefined); - var rightSide = GetValue(config, 'rightSide', undefined); - var topSide = GetValue(config, 'topSide', undefined); - var bottomSide = GetValue(config, 'bottomSide', undefined); - - if (background) { - this.addBackground(background); - } - if (panel) { - this.add(panel, 'panel', 'center', 0, true); - } - if (leftSide) { - var expand = GetValue(config, 'expand.left', true); - this.add(leftSide, 'leftSide', 'left-top', 0, { height: expand }); - } - if (rightSide) { - var expand = GetValue(config, 'expand.right', true); - this.add(rightSide, 'rightSide', 'right-top', 0, { height: expand }); - } - if (topSide) { - var expand = GetValue(config, 'expand.top', true); - this.add(topSide, 'topSide', 'left-top', 0, { width: expand }); - } - if (bottomSide) { - var expand = GetValue(config, 'expand.bottom', true); - this.add(bottomSide, 'bottomSide', 'left-bottom', 0, { width: expand }); - } - } - - reset() { - this.previousChildKey = undefined; - this.currentChildKey = 'panel'; - this.showChild('panel', true); - this.hideChild('leftSide', true); - this.hideChild('rightSide', true); - this.hideChild('topSide', true); - this.hideChild('bottomSide', true); - return this; - } -} - -Object.assign( - Sides.prototype, - ShowChildMethods, - ChildBehaviorMethods -); - -export default Sides; \ No newline at end of file diff --git a/spaces/Alpaca233/SadTalker/src/face3d/visualize.py b/spaces/Alpaca233/SadTalker/src/face3d/visualize.py deleted file mode 100644 index 23a1110806a0ddf37d4aa549c023d1c3f7114e3e..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/SadTalker/src/face3d/visualize.py +++ /dev/null @@ -1,48 +0,0 @@ -# check the sync of 3dmm feature and the audio -import cv2 -import numpy as np -from src.face3d.models.bfm import ParametricFaceModel -from src.face3d.models.facerecon_model import FaceReconModel -import torch -import subprocess, platform -import scipy.io as scio -from tqdm import tqdm - -# draft -def gen_composed_video(args, device, first_frame_coeff, coeff_path, audio_path, save_path, exp_dim=64): - - coeff_first = scio.loadmat(first_frame_coeff)['full_3dmm'] - - coeff_pred = scio.loadmat(coeff_path)['coeff_3dmm'] - - coeff_full = np.repeat(coeff_first, coeff_pred.shape[0], axis=0) # 257 - - coeff_full[:, 80:144] = coeff_pred[:, 0:64] - coeff_full[:, 224:227] = coeff_pred[:, 64:67] # 3 dim translation - coeff_full[:, 254:] = coeff_pred[:, 67:] # 3 dim translation - - tmp_video_path = '/tmp/face3dtmp.mp4' - - facemodel = FaceReconModel(args) - - video = cv2.VideoWriter(tmp_video_path, cv2.VideoWriter_fourcc(*'mp4v'), 25, (224, 224)) - - for k in tqdm(range(coeff_pred.shape[0]), 'face3d rendering:'): - cur_coeff_full = torch.tensor(coeff_full[k:k+1], device=device) - - facemodel.forward(cur_coeff_full, device) - - predicted_landmark = facemodel.pred_lm # TODO. - predicted_landmark = predicted_landmark.cpu().numpy().squeeze() - - rendered_img = facemodel.pred_face - rendered_img = 255. * rendered_img.cpu().numpy().squeeze().transpose(1,2,0) - out_img = rendered_img[:, :, :3].astype(np.uint8) - - video.write(np.uint8(out_img[:,:,::-1])) - - video.release() - - command = 'ffmpeg -v quiet -y -i {} -i {} -strict -2 -q:v 1 {}'.format(audio_path, tmp_video_path, save_path) - subprocess.call(command, shell=platform.system() != 'Windows') - diff --git a/spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/python/dqn/policies.py b/spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/python/dqn/policies.py deleted file mode 100644 index 4ecf39a5fc04b24ad1b809232b186728366987b6..0000000000000000000000000000000000000000 --- a/spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/python/dqn/policies.py +++ /dev/null @@ -1,237 +0,0 @@ -from typing import Any, Dict, List, Optional, Type - -import gym -import torch as th -from torch import nn - -from stable_baselines3.common.policies import BasePolicy, register_policy -from stable_baselines3.common.torch_layers import BaseFeaturesExtractor, FlattenExtractor, NatureCNN, create_mlp -from stable_baselines3.common.type_aliases import Schedule - - -class QNetwork(BasePolicy): - """ - Action-Value (Q-Value) network for DQN - - :param observation_space: Observation space - :param action_space: Action space - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - features_extractor: nn.Module, - features_dim: int, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - normalize_images: bool = True, - ): - super(QNetwork, self).__init__( - observation_space, - action_space, - features_extractor=features_extractor, - normalize_images=normalize_images, - ) - - if net_arch is None: - net_arch = [64, 64] - - self.net_arch = net_arch - self.activation_fn = activation_fn - self.features_extractor = features_extractor - self.features_dim = features_dim - self.normalize_images = normalize_images - action_dim = self.action_space.n # number of actions - q_net = create_mlp(self.features_dim, action_dim, self.net_arch, self.activation_fn) - self.q_net = nn.Sequential(*q_net) - - def forward(self, obs: th.Tensor) -> th.Tensor: - """ - Predict the q-values. - - :param obs: Observation - :return: The estimated Q-Value for each action. - """ - return self.q_net(self.extract_features(obs)) - - def _predict(self, observation: th.Tensor, deterministic: bool = True) -> th.Tensor: - q_values = self.forward(observation) - # Greedy action - action = q_values.argmax(dim=1).reshape(-1) - return action - - def _get_constructor_parameters(self) -> Dict[str, Any]: - data = super()._get_constructor_parameters() - - data.update( - dict( - net_arch=self.net_arch, - features_dim=self.features_dim, - activation_fn=self.activation_fn, - features_extractor=self.features_extractor, - ) - ) - return data - - -class DQNPolicy(BasePolicy): - """ - Policy class with Q-Value Net and target net for DQN - - :param observation_space: Observation space - :param action_space: Action space - :param lr_schedule: Learning rate schedule (could be constant) - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param features_extractor_class: Features extractor to use. - :param features_extractor_kwargs: Keyword arguments - to pass to the features extractor. - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - :param optimizer_class: The optimizer to use, - ``th.optim.Adam`` by default - :param optimizer_kwargs: Additional keyword arguments, - excluding the learning rate, to pass to the optimizer - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - lr_schedule: Schedule, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor, - features_extractor_kwargs: Optional[Dict[str, Any]] = None, - normalize_images: bool = True, - optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam, - optimizer_kwargs: Optional[Dict[str, Any]] = None, - ): - super(DQNPolicy, self).__init__( - observation_space, - action_space, - features_extractor_class, - features_extractor_kwargs, - optimizer_class=optimizer_class, - optimizer_kwargs=optimizer_kwargs, - ) - - if net_arch is None: - if features_extractor_class == FlattenExtractor: - net_arch = [64, 64] - else: - net_arch = [] - - self.net_arch = net_arch - self.activation_fn = activation_fn - self.normalize_images = normalize_images - - self.net_args = { - "observation_space": self.observation_space, - "action_space": self.action_space, - "net_arch": self.net_arch, - "activation_fn": self.activation_fn, - "normalize_images": normalize_images, - } - - self.q_net, self.q_net_target = None, None - self._build(lr_schedule) - - def _build(self, lr_schedule: Schedule) -> None: - """ - Create the network and the optimizer. - - :param lr_schedule: Learning rate schedule - lr_schedule(1) is the initial learning rate - """ - - self.q_net = self.make_q_net() - self.q_net_target = self.make_q_net() - self.q_net_target.load_state_dict(self.q_net.state_dict()) - - # Setup optimizer with initial learning rate - self.optimizer = self.optimizer_class(self.parameters(), lr=lr_schedule(1), **self.optimizer_kwargs) - - def make_q_net(self) -> QNetwork: - # Make sure we always have separate networks for features extractors etc - net_args = self._update_features_extractor(self.net_args, features_extractor=None) - return QNetwork(**net_args).to(self.device) - - def forward(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor: - return self._predict(obs, deterministic=deterministic) - - def _predict(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor: - return self.q_net._predict(obs, deterministic=deterministic) - - def _get_constructor_parameters(self) -> Dict[str, Any]: - data = super()._get_constructor_parameters() - - data.update( - dict( - net_arch=self.net_args["net_arch"], - activation_fn=self.net_args["activation_fn"], - lr_schedule=self._dummy_schedule, # dummy lr schedule, not needed for loading policy alone - optimizer_class=self.optimizer_class, - optimizer_kwargs=self.optimizer_kwargs, - features_extractor_class=self.features_extractor_class, - features_extractor_kwargs=self.features_extractor_kwargs, - ) - ) - return data - - -MlpPolicy = DQNPolicy - - -class CnnPolicy(DQNPolicy): - """ - Policy class for DQN when using images as input. - - :param observation_space: Observation space - :param action_space: Action space - :param lr_schedule: Learning rate schedule (could be constant) - :param net_arch: The specification of the policy and value networks. - :param activation_fn: Activation function - :param features_extractor_class: Features extractor to use. - :param normalize_images: Whether to normalize images or not, - dividing by 255.0 (True by default) - :param optimizer_class: The optimizer to use, - ``th.optim.Adam`` by default - :param optimizer_kwargs: Additional keyword arguments, - excluding the learning rate, to pass to the optimizer - """ - - def __init__( - self, - observation_space: gym.spaces.Space, - action_space: gym.spaces.Space, - lr_schedule: Schedule, - net_arch: Optional[List[int]] = None, - activation_fn: Type[nn.Module] = nn.ReLU, - features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN, - features_extractor_kwargs: Optional[Dict[str, Any]] = None, - normalize_images: bool = True, - optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam, - optimizer_kwargs: Optional[Dict[str, Any]] = None, - ): - super(CnnPolicy, self).__init__( - observation_space, - action_space, - lr_schedule, - net_arch, - activation_fn, - features_extractor_class, - features_extractor_kwargs, - normalize_images, - optimizer_class, - optimizer_kwargs, - ) - - -register_policy("MlpPolicy", MlpPolicy) -register_policy("CnnPolicy", CnnPolicy) diff --git a/spaces/Andres99/Tune-A-Video-Training-UI/app_upload.py b/spaces/Andres99/Tune-A-Video-Training-UI/app_upload.py deleted file mode 100644 index f672f555512b456d95d8f674fa832b1c9bf34309..0000000000000000000000000000000000000000 --- a/spaces/Andres99/Tune-A-Video-Training-UI/app_upload.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python - -from __future__ import annotations - -import pathlib - -import gradio as gr -import slugify - -from constants import MODEL_LIBRARY_ORG_NAME, UploadTarget -from uploader import Uploader -from utils import find_exp_dirs - - -class ModelUploader(Uploader): - def upload_model( - self, - folder_path: str, - repo_name: str, - upload_to: str, - private: bool, - delete_existing_repo: bool, - input_token: str | None = None, - ) -> str: - if not folder_path: - raise ValueError - if not repo_name: - repo_name = pathlib.Path(folder_path).name - repo_name = slugify.slugify(repo_name) - - if upload_to == UploadTarget.PERSONAL_PROFILE.value: - organization = '' - elif upload_to == UploadTarget.MODEL_LIBRARY.value: - organization = MODEL_LIBRARY_ORG_NAME - else: - raise ValueError - - return self.upload(folder_path, - repo_name, - organization=organization, - private=private, - delete_existing_repo=delete_existing_repo, - input_token=input_token) - - -def load_local_model_list() -> dict: - choices = find_exp_dirs() - return gr.update(choices=choices, value=choices[0] if choices else None) - - -def create_upload_demo(hf_token: str | None) -> gr.Blocks: - uploader = ModelUploader(hf_token) - model_dirs = find_exp_dirs() - - with gr.Blocks() as demo: - with gr.Box(): - gr.Markdown('Local Models') - reload_button = gr.Button('Reload Model List') - model_dir = gr.Dropdown( - label='Model names', - choices=model_dirs, - value=model_dirs[0] if model_dirs else None) - with gr.Box(): - gr.Markdown('Upload Settings') - with gr.Row(): - use_private_repo = gr.Checkbox(label='Private', value=True) - delete_existing_repo = gr.Checkbox( - label='Delete existing repo of the same name', value=False) - upload_to = gr.Radio(label='Upload to', - choices=[_.value for _ in UploadTarget], - value=UploadTarget.MODEL_LIBRARY.value) - model_name = gr.Textbox(label='Model Name') - input_token = gr.Text(label='Hugging Face Write Token', - placeholder='', - visible=False if hf_token else True) - upload_button = gr.Button('Upload') - gr.Markdown(f''' - - You can upload your trained model to your personal profile (i.e. https://huggingface.co/{{your_username}}/{{model_name}}) or to the public [Tune-A-Video Library](https://huggingface.co/{MODEL_LIBRARY_ORG_NAME}) (i.e. https://huggingface.co/{MODEL_LIBRARY_ORG_NAME}/{{model_name}}). - ''') - with gr.Box(): - gr.Markdown('Output message') - output_message = gr.Markdown() - - reload_button.click(fn=load_local_model_list, - inputs=None, - outputs=model_dir) - upload_button.click(fn=uploader.upload_model, - inputs=[ - model_dir, - model_name, - upload_to, - use_private_repo, - delete_existing_repo, - input_token, - ], - outputs=output_message) - - return demo - - -if __name__ == '__main__': - import os - - hf_token = os.getenv('HF_TOKEN') - demo = create_upload_demo(hf_token) - demo.queue(max_size=1).launch(share=False) diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/control_brightness.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/control_brightness.md deleted file mode 100644 index d8c0b1278f6034329d8b8299037d4d22b14b209e..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/control_brightness.md +++ /dev/null @@ -1,45 +0,0 @@ -# Control image brightness - -The Stable Diffusion pipeline is mediocre at generating images that are either very bright or dark as explained in the [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) paper. The solutions proposed in the paper are currently implemented in the [`DDIMScheduler`] which you can use to improve the lighting in your images. - - - -💡 Take a look at the paper linked above for more details about the proposed solutions! - - - -One of the solutions is to train a model with *v prediction* and *v loss*. Add the following flag to the [`train_text_to_image.py`](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py) or [`train_text_to_image_lora.py`](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py) scripts to enable `v_prediction`: - -```bash ---prediction_type="v_prediction" -``` - -For example, let's use the [`ptx0/pseudo-journey-v2`](https://huggingface.co/ptx0/pseudo-journey-v2) checkpoint which has been finetuned with `v_prediction`. - -Next, configure the following parameters in the [`DDIMScheduler`]: - -1. `rescale_betas_zero_snr=True`, rescales the noise schedule to zero terminal signal-to-noise ratio (SNR) -2. `timestep_spacing="trailing"`, starts sampling from the last timestep - -```py ->>> from diffusers import DiffusionPipeline, DDIMScheduler - ->>> pipeline = DiffusionPipeline.from_pretrained("ptx0/pseudo-journey-v2") -# switch the scheduler in the pipeline to use the DDIMScheduler - ->>> pipeline.scheduler = DDIMScheduler.from_config( -... pipeline.scheduler.config, rescale_betas_zero_snr=True, timestep_spacing="trailing" -... ) ->>> pipeline.to("cuda") -``` - -Finally, in your call to the pipeline, set `guidance_rescale` to prevent overexposure: - -```py -prompt = "A lion in galaxies, spirals, nebulae, stars, smoke, iridescent, intricate detail, octane render, 8k" -image = pipeline(prompt, guidance_rescale=0.7).images[0] -``` - -
- -
diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/inpaint.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/inpaint.md deleted file mode 100644 index 228e14e8483308dbb215cbfe18056b7c3410cae6..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/inpaint.md +++ /dev/null @@ -1,76 +0,0 @@ - - -# Text-guided image-inpainting - -[[open-in-colab]] - -The [`StableDiffusionInpaintPipeline`] allows you to edit specific parts of an image by providing a mask and a text prompt. It uses a version of Stable Diffusion, like [`runwayml/stable-diffusion-inpainting`](https://huggingface.co/runwayml/stable-diffusion-inpainting) specifically trained for inpainting tasks. - -Get started by loading an instance of the [`StableDiffusionInpaintPipeline`]: - -```python -import PIL -import requests -import torch -from io import BytesIO - -from diffusers import StableDiffusionInpaintPipeline - -pipeline = StableDiffusionInpaintPipeline.from_pretrained( - "runwayml/stable-diffusion-inpainting", - torch_dtype=torch.float16, -) -pipeline = pipeline.to("cuda") -``` - -Download an image and a mask of a dog which you'll eventually replace: - -```python -def download_image(url): - response = requests.get(url) - return PIL.Image.open(BytesIO(response.content)).convert("RGB") - - -img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" -mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" - -init_image = download_image(img_url).resize((512, 512)) -mask_image = download_image(mask_url).resize((512, 512)) -``` - -Now you can create a prompt to replace the mask with something else: - -```python -prompt = "Face of a yellow cat, high resolution, sitting on a park bench" -image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image).images[0] -``` - -`image` | `mask_image` | `prompt` | output | -:-------------------------:|:-------------------------:|:-------------------------:|-------------------------:| -drawing | drawing | ***Face of a yellow cat, high resolution, sitting on a park bench*** | drawing | - - - - -A previous experimental implementation of inpainting used a different, lower-quality process. To ensure backwards compatibility, loading a pretrained pipeline that doesn't contain the new model will still apply the old inpainting method. - - - -Check out the Spaces below to try out image inpainting yourself! - - diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_vq_diffusion.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_vq_diffusion.py deleted file mode 100644 index b92722e4d462ca675bbf11230c1c39810de48b6e..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_vq_diffusion.py +++ /dev/null @@ -1,496 +0,0 @@ -# Copyright 2023 Microsoft 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. - -from dataclasses import dataclass -from typing import Optional, Tuple, Union - -import numpy as np -import torch -import torch.nn.functional as F - -from ..configuration_utils import ConfigMixin, register_to_config -from ..utils import BaseOutput -from .scheduling_utils import SchedulerMixin - - -@dataclass -class VQDiffusionSchedulerOutput(BaseOutput): - """ - Output class for the scheduler's step function output. - - Args: - prev_sample (`torch.LongTensor` of shape `(batch size, num latent pixels)`): - Computed sample x_{t-1} of previous timestep. `prev_sample` should be used as next model input in the - denoising loop. - """ - - prev_sample: torch.LongTensor - - -def index_to_log_onehot(x: torch.LongTensor, num_classes: int) -> torch.FloatTensor: - """ - Convert batch of vector of class indices into batch of log onehot vectors - - Args: - x (`torch.LongTensor` of shape `(batch size, vector length)`): - Batch of class indices - - num_classes (`int`): - number of classes to be used for the onehot vectors - - Returns: - `torch.FloatTensor` of shape `(batch size, num classes, vector length)`: - Log onehot vectors - """ - x_onehot = F.one_hot(x, num_classes) - x_onehot = x_onehot.permute(0, 2, 1) - log_x = torch.log(x_onehot.float().clamp(min=1e-30)) - return log_x - - -def gumbel_noised(logits: torch.FloatTensor, generator: Optional[torch.Generator]) -> torch.FloatTensor: - """ - Apply gumbel noise to `logits` - """ - uniform = torch.rand(logits.shape, device=logits.device, generator=generator) - gumbel_noise = -torch.log(-torch.log(uniform + 1e-30) + 1e-30) - noised = gumbel_noise + logits - return noised - - -def alpha_schedules(num_diffusion_timesteps: int, alpha_cum_start=0.99999, alpha_cum_end=0.000009): - """ - Cumulative and non-cumulative alpha schedules. - - See section 4.1. - """ - att = ( - np.arange(0, num_diffusion_timesteps) / (num_diffusion_timesteps - 1) * (alpha_cum_end - alpha_cum_start) - + alpha_cum_start - ) - att = np.concatenate(([1], att)) - at = att[1:] / att[:-1] - att = np.concatenate((att[1:], [1])) - return at, att - - -def gamma_schedules(num_diffusion_timesteps: int, gamma_cum_start=0.000009, gamma_cum_end=0.99999): - """ - Cumulative and non-cumulative gamma schedules. - - See section 4.1. - """ - ctt = ( - np.arange(0, num_diffusion_timesteps) / (num_diffusion_timesteps - 1) * (gamma_cum_end - gamma_cum_start) - + gamma_cum_start - ) - ctt = np.concatenate(([0], ctt)) - one_minus_ctt = 1 - ctt - one_minus_ct = one_minus_ctt[1:] / one_minus_ctt[:-1] - ct = 1 - one_minus_ct - ctt = np.concatenate((ctt[1:], [0])) - return ct, ctt - - -class VQDiffusionScheduler(SchedulerMixin, ConfigMixin): - """ - The VQ-diffusion transformer outputs predicted probabilities of the initial unnoised image. - - The VQ-diffusion scheduler converts the transformer's output into a sample for the unnoised image at the previous - diffusion timestep. - - [`~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/2111.14822 - - Args: - num_vec_classes (`int`): - The number of classes of the vector embeddings of the latent pixels. Includes the class for the masked - latent pixel. - - num_train_timesteps (`int`): - Number of diffusion steps used to train the model. - - alpha_cum_start (`float`): - The starting cumulative alpha value. - - alpha_cum_end (`float`): - The ending cumulative alpha value. - - gamma_cum_start (`float`): - The starting cumulative gamma value. - - gamma_cum_end (`float`): - The ending cumulative gamma value. - """ - - order = 1 - - @register_to_config - def __init__( - self, - num_vec_classes: int, - num_train_timesteps: int = 100, - alpha_cum_start: float = 0.99999, - alpha_cum_end: float = 0.000009, - gamma_cum_start: float = 0.000009, - gamma_cum_end: float = 0.99999, - ): - self.num_embed = num_vec_classes - - # By convention, the index for the mask class is the last class index - self.mask_class = self.num_embed - 1 - - at, att = alpha_schedules(num_train_timesteps, alpha_cum_start=alpha_cum_start, alpha_cum_end=alpha_cum_end) - ct, ctt = gamma_schedules(num_train_timesteps, gamma_cum_start=gamma_cum_start, gamma_cum_end=gamma_cum_end) - - num_non_mask_classes = self.num_embed - 1 - bt = (1 - at - ct) / num_non_mask_classes - btt = (1 - att - ctt) / num_non_mask_classes - - at = torch.tensor(at.astype("float64")) - bt = torch.tensor(bt.astype("float64")) - ct = torch.tensor(ct.astype("float64")) - log_at = torch.log(at) - log_bt = torch.log(bt) - log_ct = torch.log(ct) - - att = torch.tensor(att.astype("float64")) - btt = torch.tensor(btt.astype("float64")) - ctt = torch.tensor(ctt.astype("float64")) - log_cumprod_at = torch.log(att) - log_cumprod_bt = torch.log(btt) - log_cumprod_ct = torch.log(ctt) - - self.log_at = log_at.float() - self.log_bt = log_bt.float() - self.log_ct = log_ct.float() - self.log_cumprod_at = log_cumprod_at.float() - self.log_cumprod_bt = log_cumprod_bt.float() - self.log_cumprod_ct = log_cumprod_ct.float() - - # setable values - self.num_inference_steps = None - self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy()) - - def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None): - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - num_inference_steps (`int`): - the number of diffusion steps used when generating samples with a pre-trained model. - - device (`str` or `torch.device`): - device to place the timesteps and the diffusion process parameters (alpha, beta, gamma) on. - """ - self.num_inference_steps = num_inference_steps - timesteps = np.arange(0, self.num_inference_steps)[::-1].copy() - self.timesteps = torch.from_numpy(timesteps).to(device) - - self.log_at = self.log_at.to(device) - self.log_bt = self.log_bt.to(device) - self.log_ct = self.log_ct.to(device) - self.log_cumprod_at = self.log_cumprod_at.to(device) - self.log_cumprod_bt = self.log_cumprod_bt.to(device) - self.log_cumprod_ct = self.log_cumprod_ct.to(device) - - def step( - self, - model_output: torch.FloatTensor, - timestep: torch.long, - sample: torch.LongTensor, - generator: Optional[torch.Generator] = None, - return_dict: bool = True, - ) -> Union[VQDiffusionSchedulerOutput, Tuple]: - """ - Predict the sample at the previous timestep via the reverse transition distribution i.e. Equation (11). See the - docstring for `self.q_posterior` for more in depth docs on how Equation (11) is computed. - - Args: - log_p_x_0: (`torch.FloatTensor` of shape `(batch size, num classes - 1, num latent pixels)`): - The log probabilities for the predicted classes of the initial latent pixels. Does not include a - prediction for the masked class as the initial unnoised image cannot be masked. - - t (`torch.long`): - The timestep that determines which transition matrices are used. - - x_t: (`torch.LongTensor` of shape `(batch size, num latent pixels)`): - The classes of each latent pixel at time `t` - - generator: (`torch.Generator` or None): - RNG for the noise applied to p(x_{t-1} | x_t) before it is sampled from. - - return_dict (`bool`): - option for returning tuple rather than VQDiffusionSchedulerOutput class - - Returns: - [`~schedulers.scheduling_utils.VQDiffusionSchedulerOutput`] or `tuple`: - [`~schedulers.scheduling_utils.VQDiffusionSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. - When returning a tuple, the first element is the sample tensor. - """ - if timestep == 0: - log_p_x_t_min_1 = model_output - else: - log_p_x_t_min_1 = self.q_posterior(model_output, sample, timestep) - - log_p_x_t_min_1 = gumbel_noised(log_p_x_t_min_1, generator) - - x_t_min_1 = log_p_x_t_min_1.argmax(dim=1) - - if not return_dict: - return (x_t_min_1,) - - return VQDiffusionSchedulerOutput(prev_sample=x_t_min_1) - - def q_posterior(self, log_p_x_0, x_t, t): - """ - Calculates the log probabilities for the predicted classes of the image at timestep `t-1`. I.e. Equation (11). - - Instead of directly computing equation (11), we use Equation (5) to restate Equation (11) in terms of only - forward probabilities. - - Equation (11) stated in terms of forward probabilities via Equation (5): - - Where: - - the sum is over x_0 = {C_0 ... C_{k-1}} (classes for x_0) - - p(x_{t-1} | x_t) = sum( q(x_t | x_{t-1}) * q(x_{t-1} | x_0) * p(x_0) / q(x_t | x_0) ) - - Args: - log_p_x_0: (`torch.FloatTensor` of shape `(batch size, num classes - 1, num latent pixels)`): - The log probabilities for the predicted classes of the initial latent pixels. Does not include a - prediction for the masked class as the initial unnoised image cannot be masked. - - x_t: (`torch.LongTensor` of shape `(batch size, num latent pixels)`): - The classes of each latent pixel at time `t` - - t (torch.Long): - The timestep that determines which transition matrix is used. - - Returns: - `torch.FloatTensor` of shape `(batch size, num classes, num latent pixels)`: - The log probabilities for the predicted classes of the image at timestep `t-1`. I.e. Equation (11). - """ - log_onehot_x_t = index_to_log_onehot(x_t, self.num_embed) - - log_q_x_t_given_x_0 = self.log_Q_t_transitioning_to_known_class( - t=t, x_t=x_t, log_onehot_x_t=log_onehot_x_t, cumulative=True - ) - - log_q_t_given_x_t_min_1 = self.log_Q_t_transitioning_to_known_class( - t=t, x_t=x_t, log_onehot_x_t=log_onehot_x_t, cumulative=False - ) - - # p_0(x_0=C_0 | x_t) / q(x_t | x_0=C_0) ... p_n(x_0=C_0 | x_t) / q(x_t | x_0=C_0) - # . . . - # . . . - # . . . - # p_0(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) ... p_n(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) - q = log_p_x_0 - log_q_x_t_given_x_0 - - # sum_0 = p_0(x_0=C_0 | x_t) / q(x_t | x_0=C_0) + ... + p_0(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}), ... , - # sum_n = p_n(x_0=C_0 | x_t) / q(x_t | x_0=C_0) + ... + p_n(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) - q_log_sum_exp = torch.logsumexp(q, dim=1, keepdim=True) - - # p_0(x_0=C_0 | x_t) / q(x_t | x_0=C_0) / sum_0 ... p_n(x_0=C_0 | x_t) / q(x_t | x_0=C_0) / sum_n - # . . . - # . . . - # . . . - # p_0(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) / sum_0 ... p_n(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) / sum_n - q = q - q_log_sum_exp - - # (p_0(x_0=C_0 | x_t) / q(x_t | x_0=C_0) / sum_0) * a_cumulative_{t-1} + b_cumulative_{t-1} ... (p_n(x_0=C_0 | x_t) / q(x_t | x_0=C_0) / sum_n) * a_cumulative_{t-1} + b_cumulative_{t-1} - # . . . - # . . . - # . . . - # (p_0(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) / sum_0) * a_cumulative_{t-1} + b_cumulative_{t-1} ... (p_n(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) / sum_n) * a_cumulative_{t-1} + b_cumulative_{t-1} - # c_cumulative_{t-1} ... c_cumulative_{t-1} - q = self.apply_cumulative_transitions(q, t - 1) - - # ((p_0(x_0=C_0 | x_t) / q(x_t | x_0=C_0) / sum_0) * a_cumulative_{t-1} + b_cumulative_{t-1}) * q(x_t | x_{t-1}=C_0) * sum_0 ... ((p_n(x_0=C_0 | x_t) / q(x_t | x_0=C_0) / sum_n) * a_cumulative_{t-1} + b_cumulative_{t-1}) * q(x_t | x_{t-1}=C_0) * sum_n - # . . . - # . . . - # . . . - # ((p_0(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) / sum_0) * a_cumulative_{t-1} + b_cumulative_{t-1}) * q(x_t | x_{t-1}=C_{k-1}) * sum_0 ... ((p_n(x_0=C_{k-1} | x_t) / q(x_t | x_0=C_{k-1}) / sum_n) * a_cumulative_{t-1} + b_cumulative_{t-1}) * q(x_t | x_{t-1}=C_{k-1}) * sum_n - # c_cumulative_{t-1} * q(x_t | x_{t-1}=C_k) * sum_0 ... c_cumulative_{t-1} * q(x_t | x_{t-1}=C_k) * sum_0 - log_p_x_t_min_1 = q + log_q_t_given_x_t_min_1 + q_log_sum_exp - - # For each column, there are two possible cases. - # - # Where: - # - sum(p_n(x_0))) is summing over all classes for x_0 - # - C_i is the class transitioning from (not to be confused with c_t and c_cumulative_t being used for gamma's) - # - C_j is the class transitioning to - # - # 1. x_t is masked i.e. x_t = c_k - # - # Simplifying the expression, the column vector is: - # . - # . - # . - # (c_t / c_cumulative_t) * (a_cumulative_{t-1} * p_n(x_0 = C_i | x_t) + b_cumulative_{t-1} * sum(p_n(x_0))) - # . - # . - # . - # (c_cumulative_{t-1} / c_cumulative_t) * sum(p_n(x_0)) - # - # From equation (11) stated in terms of forward probabilities, the last row is trivially verified. - # - # For the other rows, we can state the equation as ... - # - # (c_t / c_cumulative_t) * [b_cumulative_{t-1} * p(x_0=c_0) + ... + (a_cumulative_{t-1} + b_cumulative_{t-1}) * p(x_0=C_i) + ... + b_cumulative_{k-1} * p(x_0=c_{k-1})] - # - # This verifies the other rows. - # - # 2. x_t is not masked - # - # Simplifying the expression, there are two cases for the rows of the column vector, where C_j = C_i and where C_j != C_i: - # . - # . - # . - # C_j != C_i: b_t * ((b_cumulative_{t-1} / b_cumulative_t) * p_n(x_0 = c_0) + ... + ((a_cumulative_{t-1} + b_cumulative_{t-1}) / b_cumulative_t) * p_n(x_0 = C_i) + ... + (b_cumulative_{t-1} / (a_cumulative_t + b_cumulative_t)) * p_n(c_0=C_j) + ... + (b_cumulative_{t-1} / b_cumulative_t) * p_n(x_0 = c_{k-1})) - # . - # . - # . - # C_j = C_i: (a_t + b_t) * ((b_cumulative_{t-1} / b_cumulative_t) * p_n(x_0 = c_0) + ... + ((a_cumulative_{t-1} + b_cumulative_{t-1}) / (a_cumulative_t + b_cumulative_t)) * p_n(x_0 = C_i = C_j) + ... + (b_cumulative_{t-1} / b_cumulative_t) * p_n(x_0 = c_{k-1})) - # . - # . - # . - # 0 - # - # The last row is trivially verified. The other rows can be verified by directly expanding equation (11) stated in terms of forward probabilities. - return log_p_x_t_min_1 - - def log_Q_t_transitioning_to_known_class( - self, *, t: torch.int, x_t: torch.LongTensor, log_onehot_x_t: torch.FloatTensor, cumulative: bool - ): - """ - Returns the log probabilities of the rows from the (cumulative or non-cumulative) transition matrix for each - latent pixel in `x_t`. - - See equation (7) for the complete non-cumulative transition matrix. The complete cumulative transition matrix - is the same structure except the parameters (alpha, beta, gamma) are the cumulative analogs. - - Args: - t (torch.Long): - The timestep that determines which transition matrix is used. - - x_t (`torch.LongTensor` of shape `(batch size, num latent pixels)`): - The classes of each latent pixel at time `t`. - - log_onehot_x_t (`torch.FloatTensor` of shape `(batch size, num classes, num latent pixels)`): - The log one-hot vectors of `x_t` - - cumulative (`bool`): - If cumulative is `False`, we use the single step transition matrix `t-1`->`t`. If cumulative is `True`, - we use the cumulative transition matrix `0`->`t`. - - Returns: - `torch.FloatTensor` of shape `(batch size, num classes - 1, num latent pixels)`: - Each _column_ of the returned matrix is a _row_ of log probabilities of the complete probability - transition matrix. - - When non cumulative, returns `self.num_classes - 1` rows because the initial latent pixel cannot be - masked. - - Where: - - `q_n` is the probability distribution for the forward process of the `n`th latent pixel. - - C_0 is a class of a latent pixel embedding - - C_k is the class of the masked latent pixel - - non-cumulative result (omitting logarithms): - ``` - q_0(x_t | x_{t-1} = C_0) ... q_n(x_t | x_{t-1} = C_0) - . . . - . . . - . . . - q_0(x_t | x_{t-1} = C_k) ... q_n(x_t | x_{t-1} = C_k) - ``` - - cumulative result (omitting logarithms): - ``` - q_0_cumulative(x_t | x_0 = C_0) ... q_n_cumulative(x_t | x_0 = C_0) - . . . - . . . - . . . - q_0_cumulative(x_t | x_0 = C_{k-1}) ... q_n_cumulative(x_t | x_0 = C_{k-1}) - ``` - """ - if cumulative: - a = self.log_cumprod_at[t] - b = self.log_cumprod_bt[t] - c = self.log_cumprod_ct[t] - else: - a = self.log_at[t] - b = self.log_bt[t] - c = self.log_ct[t] - - if not cumulative: - # The values in the onehot vector can also be used as the logprobs for transitioning - # from masked latent pixels. If we are not calculating the cumulative transitions, - # we need to save these vectors to be re-appended to the final matrix so the values - # aren't overwritten. - # - # `P(x_t!=mask|x_{t-1=mask}) = 0` and 0 will be the value of the last row of the onehot vector - # if x_t is not masked - # - # `P(x_t=mask|x_{t-1=mask}) = 1` and 1 will be the value of the last row of the onehot vector - # if x_t is masked - log_onehot_x_t_transitioning_from_masked = log_onehot_x_t[:, -1, :].unsqueeze(1) - - # `index_to_log_onehot` will add onehot vectors for masked pixels, - # so the default one hot matrix has one too many rows. See the doc string - # for an explanation of the dimensionality of the returned matrix. - log_onehot_x_t = log_onehot_x_t[:, :-1, :] - - # this is a cheeky trick to produce the transition probabilities using log one-hot vectors. - # - # Don't worry about what values this sets in the columns that mark transitions - # to masked latent pixels. They are overwrote later with the `mask_class_mask`. - # - # Looking at the below logspace formula in non-logspace, each value will evaluate to either - # `1 * a + b = a + b` where `log_Q_t` has the one hot value in the column - # or - # `0 * a + b = b` where `log_Q_t` has the 0 values in the column. - # - # See equation 7 for more details. - log_Q_t = (log_onehot_x_t + a).logaddexp(b) - - # The whole column of each masked pixel is `c` - mask_class_mask = x_t == self.mask_class - mask_class_mask = mask_class_mask.unsqueeze(1).expand(-1, self.num_embed - 1, -1) - log_Q_t[mask_class_mask] = c - - if not cumulative: - log_Q_t = torch.cat((log_Q_t, log_onehot_x_t_transitioning_from_masked), dim=1) - - return log_Q_t - - def apply_cumulative_transitions(self, q, t): - bsz = q.shape[0] - a = self.log_cumprod_at[t] - b = self.log_cumprod_bt[t] - c = self.log_cumprod_ct[t] - - num_latent_pixels = q.shape[2] - c = c.expand(bsz, 1, num_latent_pixels) - - q = (q + a).logaddexp(b) - q = torch.cat((q, c), dim=1) - - return q diff --git a/spaces/Andy1621/uniformer_image_detection/configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_2x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_2x_coco.py deleted file mode 100644 index 4f7150ca718e2ead46eb63e74b6be06f50aa0fce..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_2x_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py' -# learning policy -lr_config = dict(step=[16, 23]) -runner = dict(type='EpochBasedRunner', max_epochs=24) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/yolo/yolov3_d53_mstrain-608_273e_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/yolo/yolov3_d53_mstrain-608_273e_coco.py deleted file mode 100644 index 9c65305baa16eb4e940d236cf45122b46b942ea9..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/yolo/yolov3_d53_mstrain-608_273e_coco.py +++ /dev/null @@ -1,124 +0,0 @@ -_base_ = '../_base_/default_runtime.py' -# model settings -model = dict( - type='YOLOV3', - pretrained='open-mmlab://darknet53', - backbone=dict(type='Darknet', depth=53, out_indices=(3, 4, 5)), - neck=dict( - type='YOLOV3Neck', - num_scales=3, - in_channels=[1024, 512, 256], - out_channels=[512, 256, 128]), - bbox_head=dict( - type='YOLOV3Head', - num_classes=80, - in_channels=[512, 256, 128], - out_channels=[1024, 512, 256], - anchor_generator=dict( - type='YOLOAnchorGenerator', - base_sizes=[[(116, 90), (156, 198), (373, 326)], - [(30, 61), (62, 45), (59, 119)], - [(10, 13), (16, 30), (33, 23)]], - strides=[32, 16, 8]), - bbox_coder=dict(type='YOLOBBoxCoder'), - featmap_strides=[32, 16, 8], - loss_cls=dict( - type='CrossEntropyLoss', - use_sigmoid=True, - loss_weight=1.0, - reduction='sum'), - loss_conf=dict( - type='CrossEntropyLoss', - use_sigmoid=True, - loss_weight=1.0, - reduction='sum'), - loss_xy=dict( - type='CrossEntropyLoss', - use_sigmoid=True, - loss_weight=2.0, - reduction='sum'), - loss_wh=dict(type='MSELoss', loss_weight=2.0, reduction='sum')), - # training and testing settings - train_cfg=dict( - assigner=dict( - type='GridAssigner', - pos_iou_thr=0.5, - neg_iou_thr=0.5, - min_pos_iou=0)), - test_cfg=dict( - nms_pre=1000, - min_bbox_size=0, - score_thr=0.05, - conf_thr=0.005, - nms=dict(type='nms', iou_threshold=0.45), - max_per_img=100)) -# dataset settings -dataset_type = 'CocoDataset' -data_root = 'data/coco/' -img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True) -train_pipeline = [ - dict(type='LoadImageFromFile', to_float32=True), - dict(type='LoadAnnotations', with_bbox=True), - dict(type='PhotoMetricDistortion'), - dict( - type='Expand', - mean=img_norm_cfg['mean'], - to_rgb=img_norm_cfg['to_rgb'], - ratio_range=(1, 2)), - dict( - type='MinIoURandomCrop', - min_ious=(0.4, 0.5, 0.6, 0.7, 0.8, 0.9), - min_crop_size=0.3), - dict(type='Resize', img_scale=[(320, 320), (608, 608)], keep_ratio=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='DefaultFormatBundle'), - dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(608, 608), - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']) - ]) -] -data = dict( - samples_per_gpu=8, - workers_per_gpu=4, - train=dict( - type=dataset_type, - ann_file=data_root + 'annotations/instances_train2017.json', - img_prefix=data_root + 'train2017/', - pipeline=train_pipeline), - val=dict( - type=dataset_type, - ann_file=data_root + 'annotations/instances_val2017.json', - img_prefix=data_root + 'val2017/', - pipeline=test_pipeline), - test=dict( - type=dataset_type, - ann_file=data_root + 'annotations/instances_val2017.json', - img_prefix=data_root + 'val2017/', - pipeline=test_pipeline)) -# optimizer -optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) -optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) -# learning policy -lr_config = dict( - policy='step', - warmup='linear', - warmup_iters=2000, # same as burn-in in darknet - warmup_ratio=0.1, - step=[218, 246]) -# runtime settings -runner = dict(type='EpochBasedRunner', max_epochs=273) -evaluation = dict(interval=1, metric=['bbox']) diff --git a/spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/util/slio.py b/spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/util/slio.py deleted file mode 100644 index 72c1f0f7b82cdc931d381feef64fe15815ba657e..0000000000000000000000000000000000000000 --- a/spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/util/slio.py +++ /dev/null @@ -1,177 +0,0 @@ -# ========================================================== -# Modified from mmcv -# ========================================================== - -import json -import pickle -from abc import ABCMeta, abstractmethod -from pathlib import Path - -import yaml - -try: - from yaml import CLoader as Loader, CDumper as Dumper -except ImportError: - from yaml import Loader, Dumper - - -# =========================== -# Rigister handler -# =========================== - - -class BaseFileHandler(metaclass=ABCMeta): - @abstractmethod - def load_from_fileobj(self, file, **kwargs): - pass - - @abstractmethod - def dump_to_fileobj(self, obj, file, **kwargs): - pass - - @abstractmethod - def dump_to_str(self, obj, **kwargs): - pass - - def load_from_path(self, filepath, mode="r", **kwargs): - with open(filepath, mode) as f: - return self.load_from_fileobj(f, **kwargs) - - def dump_to_path(self, obj, filepath, mode="w", **kwargs): - with open(filepath, mode) as f: - self.dump_to_fileobj(obj, f, **kwargs) - - -class JsonHandler(BaseFileHandler): - def load_from_fileobj(self, file): - return json.load(file) - - def dump_to_fileobj(self, obj, file, **kwargs): - json.dump(obj, file, **kwargs) - - def dump_to_str(self, obj, **kwargs): - return json.dumps(obj, **kwargs) - - -class PickleHandler(BaseFileHandler): - def load_from_fileobj(self, file, **kwargs): - return pickle.load(file, **kwargs) - - def load_from_path(self, filepath, **kwargs): - return super(PickleHandler, self).load_from_path(filepath, mode="rb", **kwargs) - - def dump_to_str(self, obj, **kwargs): - kwargs.setdefault("protocol", 2) - return pickle.dumps(obj, **kwargs) - - def dump_to_fileobj(self, obj, file, **kwargs): - kwargs.setdefault("protocol", 2) - pickle.dump(obj, file, **kwargs) - - def dump_to_path(self, obj, filepath, **kwargs): - super(PickleHandler, self).dump_to_path(obj, filepath, mode="wb", **kwargs) - - -class YamlHandler(BaseFileHandler): - def load_from_fileobj(self, file, **kwargs): - kwargs.setdefault("Loader", Loader) - return yaml.load(file, **kwargs) - - def dump_to_fileobj(self, obj, file, **kwargs): - kwargs.setdefault("Dumper", Dumper) - yaml.dump(obj, file, **kwargs) - - def dump_to_str(self, obj, **kwargs): - kwargs.setdefault("Dumper", Dumper) - return yaml.dump(obj, **kwargs) - - -file_handlers = { - "json": JsonHandler(), - "yaml": YamlHandler(), - "yml": YamlHandler(), - "pickle": PickleHandler(), - "pkl": PickleHandler(), -} - -# =========================== -# load and dump -# =========================== - - -def is_str(x): - """Whether the input is an string instance. - - Note: This method is deprecated since python 2 is no longer supported. - """ - return isinstance(x, str) - - -def slload(file, file_format=None, **kwargs): - """Load data from json/yaml/pickle files. - - This method provides a unified api for loading data from serialized files. - - Args: - file (str or :obj:`Path` or file-like object): Filename or a file-like - object. - file_format (str, optional): If not specified, the file format will be - inferred from the file extension, otherwise use the specified one. - Currently supported formats include "json", "yaml/yml" and - "pickle/pkl". - - Returns: - The content from the file. - """ - if isinstance(file, Path): - file = str(file) - if file_format is None and is_str(file): - file_format = file.split(".")[-1] - if file_format not in file_handlers: - raise TypeError(f"Unsupported format: {file_format}") - - handler = file_handlers[file_format] - if is_str(file): - obj = handler.load_from_path(file, **kwargs) - elif hasattr(file, "read"): - obj = handler.load_from_fileobj(file, **kwargs) - else: - raise TypeError('"file" must be a filepath str or a file-object') - return obj - - -def sldump(obj, file=None, file_format=None, **kwargs): - """Dump data to json/yaml/pickle strings or files. - - This method provides a unified api for dumping data as strings or to files, - and also supports custom arguments for each file format. - - Args: - obj (any): The python object to be dumped. - file (str or :obj:`Path` or file-like object, optional): If not - specified, then the object is dump to a str, otherwise to a file - specified by the filename or file-like object. - file_format (str, optional): Same as :func:`load`. - - Returns: - bool: True for success, False otherwise. - """ - if isinstance(file, Path): - file = str(file) - if file_format is None: - if is_str(file): - file_format = file.split(".")[-1] - elif file is None: - raise ValueError("file_format must be specified since file is None") - if file_format not in file_handlers: - raise TypeError(f"Unsupported format: {file_format}") - - handler = file_handlers[file_format] - if file is None: - return handler.dump_to_str(obj, **kwargs) - elif is_str(file): - handler.dump_to_path(obj, file, **kwargs) - elif hasattr(file, "write"): - handler.dump_to_fileobj(obj, file, **kwargs) - else: - raise TypeError('"file" must be a filename str or a file-object') diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/network/lazy_wheel.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/network/lazy_wheel.py deleted file mode 100644 index 82ec50d5106ff0ac41dd1c03c2a789dbc468c401..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/network/lazy_wheel.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Lazy ZIP over HTTP""" - -__all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"] - -from bisect import bisect_left, bisect_right -from contextlib import contextmanager -from tempfile import NamedTemporaryFile -from typing import Any, Dict, Generator, List, Optional, Tuple -from zipfile import BadZipFile, ZipFile - -from pip._vendor.packaging.utils import canonicalize_name -from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response - -from pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution -from pip._internal.network.session import PipSession -from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks - - -class HTTPRangeRequestUnsupported(Exception): - pass - - -def dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution: - """Return a distribution object from the given wheel URL. - - This uses HTTP range requests to only fetch the portion of the wheel - containing metadata, just enough for the object to be constructed. - If such requests are not supported, HTTPRangeRequestUnsupported - is raised. - """ - with LazyZipOverHTTP(url, session) as zf: - # For read-only ZIP files, ZipFile only needs methods read, - # seek, seekable and tell, not the whole IO protocol. - wheel = MemoryWheel(zf.name, zf) # type: ignore - # After context manager exit, wheel.name - # is an invalid file by intention. - return get_wheel_distribution(wheel, canonicalize_name(name)) - - -class LazyZipOverHTTP: - """File-like object mapped to a ZIP file over HTTP. - - This uses HTTP range requests to lazily fetch the file's content, - which is supposed to be fed to ZipFile. If such requests are not - supported by the server, raise HTTPRangeRequestUnsupported - during initialization. - """ - - def __init__( - self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE - ) -> None: - head = session.head(url, headers=HEADERS) - raise_for_status(head) - assert head.status_code == 200 - self._session, self._url, self._chunk_size = session, url, chunk_size - self._length = int(head.headers["Content-Length"]) - self._file = NamedTemporaryFile() - self.truncate(self._length) - self._left: List[int] = [] - self._right: List[int] = [] - if "bytes" not in head.headers.get("Accept-Ranges", "none"): - raise HTTPRangeRequestUnsupported("range request is not supported") - self._check_zip() - - @property - def mode(self) -> str: - """Opening mode, which is always rb.""" - return "rb" - - @property - def name(self) -> str: - """Path to the underlying file.""" - return self._file.name - - def seekable(self) -> bool: - """Return whether random access is supported, which is True.""" - return True - - def close(self) -> None: - """Close the file.""" - self._file.close() - - @property - def closed(self) -> bool: - """Whether the file is closed.""" - return self._file.closed - - def read(self, size: int = -1) -> bytes: - """Read up to size bytes from the object and return them. - - As a convenience, if size is unspecified or -1, - all bytes until EOF are returned. Fewer than - size bytes may be returned if EOF is reached. - """ - download_size = max(size, self._chunk_size) - start, length = self.tell(), self._length - stop = length if size < 0 else min(start + download_size, length) - start = max(0, stop - download_size) - self._download(start, stop - 1) - return self._file.read(size) - - def readable(self) -> bool: - """Return whether the file is readable, which is True.""" - return True - - def seek(self, offset: int, whence: int = 0) -> int: - """Change stream position and return the new absolute position. - - Seek to offset relative position indicated by whence: - * 0: Start of stream (the default). pos should be >= 0; - * 1: Current position - pos may be negative; - * 2: End of stream - pos usually negative. - """ - return self._file.seek(offset, whence) - - def tell(self) -> int: - """Return the current position.""" - return self._file.tell() - - def truncate(self, size: Optional[int] = None) -> int: - """Resize the stream to the given size in bytes. - - If size is unspecified resize to the current position. - The current stream position isn't changed. - - Return the new file size. - """ - return self._file.truncate(size) - - def writable(self) -> bool: - """Return False.""" - return False - - def __enter__(self) -> "LazyZipOverHTTP": - self._file.__enter__() - return self - - def __exit__(self, *exc: Any) -> None: - self._file.__exit__(*exc) - - @contextmanager - def _stay(self) -> Generator[None, None, None]: - """Return a context manager keeping the position. - - At the end of the block, seek back to original position. - """ - pos = self.tell() - try: - yield - finally: - self.seek(pos) - - def _check_zip(self) -> None: - """Check and download until the file is a valid ZIP.""" - end = self._length - 1 - for start in reversed(range(0, end, self._chunk_size)): - self._download(start, end) - with self._stay(): - try: - # For read-only ZIP files, ZipFile only needs - # methods read, seek, seekable and tell. - ZipFile(self) # type: ignore - except BadZipFile: - pass - else: - break - - def _stream_response( - self, start: int, end: int, base_headers: Dict[str, str] = HEADERS - ) -> Response: - """Return HTTP response to a range request from start to end.""" - headers = base_headers.copy() - headers["Range"] = f"bytes={start}-{end}" - # TODO: Get range requests to be correctly cached - headers["Cache-Control"] = "no-cache" - return self._session.get(self._url, headers=headers, stream=True) - - def _merge( - self, start: int, end: int, left: int, right: int - ) -> Generator[Tuple[int, int], None, None]: - """Return a generator of intervals to be fetched. - - Args: - start (int): Start of needed interval - end (int): End of needed interval - left (int): Index of first overlapping downloaded data - right (int): Index after last overlapping downloaded data - """ - lslice, rslice = self._left[left:right], self._right[left:right] - i = start = min([start] + lslice[:1]) - end = max([end] + rslice[-1:]) - for j, k in zip(lslice, rslice): - if j > i: - yield i, j - 1 - i = k + 1 - if i <= end: - yield i, end - self._left[left:right], self._right[left:right] = [start], [end] - - def _download(self, start: int, end: int) -> None: - """Download bytes from start to end inclusively.""" - with self._stay(): - left = bisect_left(self._right, start) - right = bisect_right(self._left, end) - for start, end in self._merge(start, end, left, right): - response = self._stream_response(start, end) - response.raise_for_status() - self.seek(start) - for chunk in response_chunks(response, self._chunk_size): - self._file.write(chunk) diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/chardet/codingstatemachinedict.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/chardet/codingstatemachinedict.py deleted file mode 100644 index 7a3c4c7e3fe16e91225a87cbc58b8bbd798f9cc1..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/chardet/codingstatemachinedict.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import TYPE_CHECKING, Tuple - -if TYPE_CHECKING: - # TypedDict was introduced in Python 3.8. - # - # TODO: Remove the else block and TYPE_CHECKING check when dropping support - # for Python 3.7. - from typing import TypedDict - - class CodingStateMachineDict(TypedDict, total=False): - class_table: Tuple[int, ...] - class_factor: int - state_table: Tuple[int, ...] - char_len_table: Tuple[int, ...] - name: str - language: str # Optional key - -else: - CodingStateMachineDict = dict diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/spinner.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/spinner.py deleted file mode 100644 index 91ea630e10f893bf5d6b17fcd9a1fedcecee6f02..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/spinner.py +++ /dev/null @@ -1,137 +0,0 @@ -from typing import cast, List, Optional, TYPE_CHECKING, Union - -from ._spinners import SPINNERS -from .measure import Measurement -from .table import Table -from .text import Text - -if TYPE_CHECKING: - from .console import Console, ConsoleOptions, RenderResult, RenderableType - from .style import StyleType - - -class Spinner: - """A spinner animation. - - Args: - name (str): Name of spinner (run python -m rich.spinner). - text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". - style (StyleType, optional): Style for spinner animation. Defaults to None. - speed (float, optional): Speed factor for animation. Defaults to 1.0. - - Raises: - KeyError: If name isn't one of the supported spinner animations. - """ - - def __init__( - self, - name: str, - text: "RenderableType" = "", - *, - style: Optional["StyleType"] = None, - speed: float = 1.0, - ) -> None: - try: - spinner = SPINNERS[name] - except KeyError: - raise KeyError(f"no spinner called {name!r}") - self.text: "Union[RenderableType, Text]" = ( - Text.from_markup(text) if isinstance(text, str) else text - ) - self.frames = cast(List[str], spinner["frames"])[:] - self.interval = cast(float, spinner["interval"]) - self.start_time: Optional[float] = None - self.style = style - self.speed = speed - self.frame_no_offset: float = 0.0 - self._update_speed = 0.0 - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> "RenderResult": - yield self.render(console.get_time()) - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> Measurement: - text = self.render(0) - return Measurement.get(console, options, text) - - def render(self, time: float) -> "RenderableType": - """Render the spinner for a given time. - - Args: - time (float): Time in seconds. - - Returns: - RenderableType: A renderable containing animation frame. - """ - if self.start_time is None: - self.start_time = time - - frame_no = ((time - self.start_time) * self.speed) / ( - self.interval / 1000.0 - ) + self.frame_no_offset - frame = Text( - self.frames[int(frame_no) % len(self.frames)], style=self.style or "" - ) - - if self._update_speed: - self.frame_no_offset = frame_no - self.start_time = time - self.speed = self._update_speed - self._update_speed = 0.0 - - if not self.text: - return frame - elif isinstance(self.text, (str, Text)): - return Text.assemble(frame, " ", self.text) - else: - table = Table.grid(padding=1) - table.add_row(frame, self.text) - return table - - def update( - self, - *, - text: "RenderableType" = "", - style: Optional["StyleType"] = None, - speed: Optional[float] = None, - ) -> None: - """Updates attributes of a spinner after it has been started. - - Args: - text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". - style (StyleType, optional): Style for spinner animation. Defaults to None. - speed (float, optional): Speed factor for animation. Defaults to None. - """ - if text: - self.text = Text.from_markup(text) if isinstance(text, str) else text - if style: - self.style = style - if speed: - self._update_speed = speed - - -if __name__ == "__main__": # pragma: no cover - from time import sleep - - from .columns import Columns - from .panel import Panel - from .live import Live - - all_spinners = Columns( - [ - Spinner(spinner_name, text=Text(repr(spinner_name), style="green")) - for spinner_name in sorted(SPINNERS.keys()) - ], - column_first=True, - expand=True, - ) - - with Live( - Panel(all_spinners, title="Spinners", border_style="blue"), - refresh_per_second=20, - ) as live: - while True: - sleep(0.1) diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/debug.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/debug.py deleted file mode 100644 index daf1660f0d821143e388d37532a39ddfd2ca0347..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/debug.py +++ /dev/null @@ -1,5 +0,0 @@ -import os - -# If DISTUTILS_DEBUG is anything other than the empty string, we run in -# debug mode. -DEBUG = os.environ.get('DISTUTILS_DEBUG') diff --git a/spaces/Atualli/mediapipe-pose-estimation/README.md b/spaces/Atualli/mediapipe-pose-estimation/README.md deleted file mode 100644 index 257a413265d059cf7cd0e50c35b4c24b6592b09c..0000000000000000000000000000000000000000 --- a/spaces/Atualli/mediapipe-pose-estimation/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Mediapipe Pose Estimation -emoji: 👁 -colorFrom: blue -colorTo: gray -sdk: gradio -sdk_version: 3.36.1 -app_file: app.py -pinned: false -duplicated_from: hysts/mediapipe-pose-estimation ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_R_50_FPN_400ep_LSJ.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_R_50_FPN_400ep_LSJ.py deleted file mode 100644 index 97586b8f5330a9d995a0bffd1f5e7bd5b5656462..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_R_50_FPN_400ep_LSJ.py +++ /dev/null @@ -1,14 +0,0 @@ -from .mask_rcnn_R_50_FPN_100ep_LSJ import ( - dataloader, - lr_multiplier, - model, - optimizer, - train, -) - -train.max_iter *= 4 # 100ep -> 400ep - -lr_multiplier.scheduler.milestones = [ - milestone * 4 for milestone in lr_multiplier.scheduler.milestones -] -lr_multiplier.scheduler.num_updates = train.max_iter diff --git a/spaces/Babelscape/mrebel-demo/app.py b/spaces/Babelscape/mrebel-demo/app.py deleted file mode 100644 index ee3717670d2436b3e915157161fa8b6deb07e911..0000000000000000000000000000000000000000 --- a/spaces/Babelscape/mrebel-demo/app.py +++ /dev/null @@ -1,123 +0,0 @@ -import streamlit as st -from datasets import load_dataset -from transformers import AutoModelForSeq2SeqLM, AutoTokenizer -from time import time -import torch - - -def load_tok_and_data(lan): - st_time = time() - tokenizer = AutoTokenizer.from_pretrained("Babelscape/mrebel-large", tgt_lang="tp_XX") - tokenizer._src_lang = _Tokens[lan] - tokenizer.cur_lang_code_id = tokenizer.convert_tokens_to_ids(_Tokens[lan]) - tokenizer.set_src_lang_special_tokens(_Tokens[lan]) - dataset = load_dataset('Babelscape/SREDFM', lan, split="test", streaming=True) - dataset = [example for example in dataset.take(1001)] - return (tokenizer, dataset) - -@st.cache_resource -def load_model(): - st_time = time() - print("+++++ loading Model", time() - st_time) - model = AutoModelForSeq2SeqLM.from_pretrained("Babelscape/mrebel-large") - if torch.cuda.is_available(): - _ = model.to("cuda:0") # comment if no GPU available - _ = model.eval() - print("+++++ loaded model", time() - st_time) - return model - -def extract_triplets_typed(text): - triplets = [] - relation = '' - text = text.strip() - current = 'x' - subject, relation, object_, object_type, subject_type = '','','','','' - - for token in text.replace("", "").replace("", "").replace("", "").replace("tp_XX", "").replace("__en__", "").split(): - if token == "" or token == "": - current = 't' - if relation != '': - triplets.append({'head': subject.strip(), 'head_type': subject_type, 'type': relation.strip(),'tail': object_.strip(), 'tail_type': object_type}) - relation = '' - subject = '' - elif token.startswith("<") and token.endswith(">"): - if current == 't' or current == 'o': - current = 's' - if relation != '': - triplets.append({'head': subject.strip(), 'head_type': subject_type, 'type': relation.strip(),'tail': object_.strip(), 'tail_type': object_type}) - object_ = '' - subject_type = token[1:-1] - else: - current = 'o' - object_type = token[1:-1] - relation = '' - else: - if current == 't': - subject += ' ' + token - elif current == 's': - object_ += ' ' + token - elif current == 'o': - relation += ' ' + token - if subject != '' and relation != '' and object_ != '' and object_type != '' and subject_type != '': - triplets.append({'head': subject.strip(), 'head_type': subject_type, 'type': relation.strip(),'tail': object_.strip(), 'tail_type': object_type}) - return triplets - -st.markdown("""This is a demo for the ACL 2023 paper [RED$^{FM}$: a Filtered and Multilingual Relation Extraction Dataset](https://arxiv.org/abs/2306.09802). The pre-trained model is able to extract triplets for up to 400 relation types from Wikidata or be used in downstream Relation Extraction task by fine-tuning. Find the model card [here](https://huggingface.co/Babelscape/mrebel-large). Read more about it in the [paper](https://arxiv.org/abs/2306.09802) and in the original [repository](https://github.com/Babelscape/rebel#REDFM).""") - -model = load_model() - -lan = st.selectbox( - 'Select a Language', - ('ar', 'ca', 'de', 'el', 'en', 'es', 'fr', 'hi', 'it', 'ja', 'ko', 'nl', 'pl', 'pt', 'ru', 'sv', 'vi', 'zh'), index=1) - -_Tokens = {'en': 'en_XX', 'de': 'de_DE', 'ca': 'ca_XX', 'ar': 'ar_AR', 'el': 'el_EL', 'es': 'es_XX', 'it': 'it_IT', 'ja': 'ja_XX', 'ko': 'ko_KR', 'hi': 'hi_IN', 'pt': 'pt_XX', 'ru': 'ru_RU', 'pl': 'pl_PL', 'zh': 'zh_CN', 'fr': 'fr_XX', 'vi': 'vi_VN', 'sv':'sv_SE'} - -tokenizer, dataset = load_tok_and_data(lan) - -agree = st.checkbox('Free input', False) -if agree: - text = st.text_input('Input text (current example in catalan)', 'Els Red Hot Chili Peppers es van formar a Los Angeles per Kiedis, Flea, el guitarrista Hillel Slovak i el bateria Jack Irons.') - print(text) -else: - dataset_example = st.slider('dataset id', 0, 1000, 0) - text = dataset[dataset_example]['text'] -length_penalty = st.slider('length_penalty', 0, 10, 1) -num_beams = st.slider('num_beams', 1, 20, 3) -num_return_sequences = st.slider('num_return_sequences', 1, num_beams, 2) - -gen_kwargs = { - "max_length": 256, - "length_penalty": length_penalty, - "num_beams": num_beams, - "num_return_sequences": num_return_sequences, - "forced_bos_token_id": None, -} - -model_inputs = tokenizer(text, max_length=256, padding=True, truncation=True, return_tensors = 'pt') -generated_tokens = model.generate( - model_inputs["input_ids"].to(model.device), - attention_mask=model_inputs["attention_mask"].to(model.device), - decoder_start_token_id = tokenizer.convert_tokens_to_ids("tp_XX"), - **gen_kwargs, -) - -decoded_preds = tokenizer.batch_decode(generated_tokens, skip_special_tokens=False) -st.title('Input text') - -st.write(text) - -if not agree: - st.title('Silver output') - entities = dataset[dataset_example]['entities'] - relations =[] - for trip in dataset[dataset_example]['relations']: - relations.append({'subject': entities[trip['subject']], 'predicate': trip['predicate'], 'object': entities[trip['object']]}) - st.write(relations) - -st.title('Prediction text') -decoded_preds = [text.replace('', '').replace('', '').replace('', '') for text in decoded_preds] -st.write(decoded_preds) - -for idx, sentence in enumerate(decoded_preds): - st.title(f'Prediction triplets sentence {idx}') - st.write(extract_triplets_typed(sentence)) \ No newline at end of file diff --git a/spaces/Bambicita/rvc-models/app.py b/spaces/Bambicita/rvc-models/app.py deleted file mode 100644 index 8f1dd8103616f47920fdd5a43d91e847250a3833..0000000000000000000000000000000000000000 --- a/spaces/Bambicita/rvc-models/app.py +++ /dev/null @@ -1,188 +0,0 @@ -import os -import json -import argparse -import traceback -import logging -import gradio as gr -import numpy as np -import librosa -import torch -import asyncio -import edge_tts -from datetime import datetime -from fairseq import checkpoint_utils -from infer_pack.models import SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono -from vc_infer_pipeline import VC -from config import ( - is_half, - device -) -logging.getLogger("numba").setLevel(logging.WARNING) -limitation = os.getenv("SYSTEM") == "spaces" # limit audio length in huggingface spaces - -def create_vc_fn(tgt_sr, net_g, vc, if_f0, file_index, file_big_npy): - def vc_fn( - input_audio, - f0_up_key, - f0_method, - index_rate, - tts_mode, - tts_text, - tts_voice - ): - try: - 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) - else: - if args.files: - audio, sr = librosa.load(input_audio, sr=16000, mono=True) - else: - 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) - times = [0, 0, 0] - f0_up_key = int(f0_up_key) - audio_opt = vc.pipeline( - hubert_model, - net_g, - 0, - audio, - times, - f0_up_key, - f0_method, - file_index, - file_big_npy, - index_rate, - if_f0, - ) - print( - f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s" - ) - return "Success", (tgt_sr, audio_opt) - except: - info = traceback.format_exc() - print(info) - return info, (None, None) - return vc_fn - -def load_hubert(): - global hubert_model - models, _, _ = checkpoint_utils.load_model_ensemble_and_task( - ["hubert_base.pt"], - suffix="", - ) - hubert_model = models[0] - hubert_model = hubert_model.to(device) - if is_half: - hubert_model = hubert_model.half() - else: - hubert_model = hubert_model.float() - hubert_model.eval() - -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) - else: - return gr.Audio.update(visible=True), gr.Textbox.update(visible=False), gr.Dropdown.update(visible=False) - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--api', action="store_true", default=False) - parser.add_argument("--share", action="store_true", default=False, help="share gradio app") - parser.add_argument("--files", action="store_true", default=False, help="load audio from path") - args, unknown = parser.parse_known_args() - load_hubert() - models = [] - tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices()) - voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list] - with open("weights/model_info.json", "r", encoding="utf-8") as f: - models_info = json.load(f) - for name, info in models_info.items(): - if not info['enable']: - continue - title = info['title'] - author = info.get("author", None) - cover = f"weights/{name}/{info['cover']}" - index = f"weights/{name}/{info['feature_retrieval_library']}" - npy = f"weights/{name}/{info['feature_file']}" - cpt = torch.load(f"weights/{name}/{name}.pth", map_location="cpu") - tgt_sr = cpt["config"][-1] - cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk - if_f0 = cpt.get("f0", 1) - if if_f0 == 1: - net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=is_half) - else: - net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) - del net_g.enc_q - print(net_g.load_state_dict(cpt["weight"], strict=False)) # 不加这一行清不干净, 真奇葩 - net_g.eval().to(device) - if is_half: - net_g = net_g.half() - else: - net_g = net_g.float() - vc = VC(tgt_sr, device, is_half) - models.append((name, title, author, cover, create_vc_fn(tgt_sr, net_g, vc, if_f0, index, npy))) - with gr.Blocks() as app: - gr.Markdown( - "#
RVC Models (Outdated)\n" - "##
The input audio should be clean and pure voice without background music.\n" - "###
Updated Repository: [NEW RVC Models](https://huggingface.co/spaces/ArkanDash/rvc-models-new).\n" - "####
Recommended to use the Google Colab version for more feature.\n" - "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=ArkanDash.Rvc-Models)\n\n" - "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1hx6kKvIuv5XNY1Gai2PEuZhpO5z6xpVh?usp=sharing)\n\n" - "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)" - ) - with gr.Tabs(): - for (name, title, author, cover, vc_fn) in models: - with gr.TabItem(name): - with gr.Row(): - gr.Markdown( - '
' - f'
{title}
\n'+ - (f'
Model author: {author}
' if author else "")+ - (f'' if cover else "")+ - '
' - ) - with gr.Row(): - with gr.Column(): - if args.files: - vc_input = gr.Textbox(label="Input audio path") - else: - vc_input = gr.Audio(label="Input audio"+' (less than 20 seconds)' if limitation else '') - vc_transpose = gr.Number(label="Transpose", value=0) - vc_f0method = gr.Radio( - label="Pitch extraction algorithm, PM is fast but Harvest is better for low frequencies", - choices=["pm", "harvest"], - value="pm", - interactive=True, - ) - vc_index_ratio = gr.Slider( - minimum=0, - maximum=1, - label="Retrieval feature ratio", - value=0.6, - interactive=True, - ) - 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(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female") - 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_transpose, vc_f0method, vc_index_ratio, tts_mode, tts_text, tts_voice], [vc_output1, vc_output2]) - tts_mode.change(change_to_tts_mode, [tts_mode], [vc_input, tts_text, tts_voice]) - app.queue(concurrency_count=1, max_size=20, api_open=args.api).launch(share=args.share) \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Gratis Brawl Stars.md b/spaces/Benson/text-generation/Examples/Descargar Gratis Brawl Stars.md deleted file mode 100644 index 9c1073d240b742140738de0a9ae85d08d32e7043..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Gratis Brawl Stars.md +++ /dev/null @@ -1,71 +0,0 @@ -
-

Descargar Hack jugar juntos: Cómo obtener dinero ilimitado, diamantes y gemas en el juego social popular

-

¿Te encanta jugar Play Together, el juego social donde puedes conocer amigos de todo el mundo, jugar minijuegos, decorar tu casa, vestir a tu personaje y criar mascotas? Si es así, es posible que se pregunte cómo obtener más dinero, diamantes y gemas en el juego sin gastar dinero real. Bueno, usted está de suerte porque en este artículo, le mostraremos cómo descargar hack jugar juntos y obtener recursos ilimitados en su cuenta. ¡Sigue leyendo para saber más!

-

descargar gratis brawl stars


Download ->->->-> https://bltlly.com/2v6LOZ



-

¿Qué es jugar juntos?

-

Play Together es un mundo virtual donde puedes chatear con amigos, divertirte y expresarte. Puedes hacer todo tipo de cosas en el juego, como:

-

Un mundo virtual donde puedes conocer amigos de todo el mundo

-

Puede unirse a un servidor con jugadores de diferentes países y regiones, y comunicarse con ellos mediante el chat de texto o voz. También puede invitar a sus amigos a su casa para una fiesta o para jugar minijuegos juntos. ¡Cuanto más, mejor!

-

Una variedad de mini-juegos, actividades y opciones de personalización

-

Puedes elegir entre muchos minijuegos diferentes para jugar con tus amigos u otros jugadores en línea. Usted puede correr a la línea de meta, se enfrentan a un enjambre de zombies, tirar abajo en una batalla real, y más. También puede explorar diferentes lugares en el mundo del juego, como la playa, el camping, el parque de atracciones y la ciudad. También puedes personalizar tu personaje de muchas maneras y expresar tu personalidad. Puedes cambiar tu ropa, estilo de cabello, accesorios, expresiones faciales y poses. También puedes decorar tu casa con todo tipo de muebles y artículos que se adapten a tu gusto.

-

Un juego gratuito con compras en la aplicación

- -

¿Por qué necesita hack jugar juntos?

-

Si bien Play Together es un juego divertido y divertido, también puede ser frustrante si no tienes suficiente dinero, diamantes o gemas. Es posible que te sientas limitado en lo que puedes hacer o comprar en el juego. También puedes sentirte excluido o inferior en comparación con otros jugadores que tienen más recursos que tú. Es por eso que es posible que desee utilizar el juego hack juntos para obtener dinero ilimitado, diamantes y gemas en su cuenta. Estos son algunos de los beneficios de usar hack play juntos:

-

Para disfrutar del juego sin gastar dinero real

Con hack jugar juntos, usted no tiene que gastar dinero real para obtener más dinero, diamantes, o gemas en el juego. Puedes conseguir tantos como quieras gratis y usarlos para comprar lo que quieras en el juego. También puedes ahorrar dinero para otras cosas que te importan más en la vida real.

-

Para desbloquear todos los artículos, trajes, mascotas y muebles

-

Con hack jugar juntos, puede desbloquear todos los artículos, trajes, mascotas y muebles que están disponibles en el juego. No tienes que esperar a que llegue un determinado nivel o evento. También puedes mezclarlos y combinarlos para crear tu propio estilo y apariencia únicos. También puedes impresionar a tus amigos y otros jugadores con tu colección y mostrar tu creatividad.

-

-

Para capturar peces e insectos raros para su colección

-

Con hack jugar juntos, se puede coger peces raros e insectos que son difíciles de encontrar en el juego. No tienes que pasar horas pescando o cazando para ellos. También puedes usarlos para decorar tu casa o venderlos por más dinero. También puedes completar tu colección y ganar logros y recompensas.

-

Cómo descargar hack jugar juntos?

-

Ahora que usted sabe por qué necesita hack jugar juntos, es posible que se pregunte cómo descargarlo y usarlo. Bueno, hay dos formas de hacerlo: la forma ilegal y la forma legal. Veamos cuáles son y cuáles son los riesgos y beneficios de cada uno.

- -

La forma ilegal de descargar el juego de hackeo es usar programas, aplicaciones o métodos que no están autorizados por los desarrolladores de juegos o las tiendas de aplicaciones. Estos incluyen cosas como:

-
    -
  • Herramientas de hacking que inyectan código en el juego o modifican sus archivos
  • -
  • Aplicaciones modificadas que han sido manipuladas o alteradas desde la versión original
  • -
  • Métodos no autorizados que explotan fallos o errores en el juego
  • -
-

Si bien estos métodos pueden parecer tentadores, también tienen muchos riesgos. Algunos de ellos son:

-
    -
  • Obtener virus, malware o spyware en su dispositivo que pueden dañar sus datos o privacidad
  • -
  • Ser estafado por sitios web o aplicaciones falsas que piden su información personal o detalles de pago
  • -
  • Ser expulsado del juego o perder tu cuenta por violar los términos del servicio
  • -
-

Por lo tanto, no recomendamos usar estos métodos ya que no son seguros, confiables o éticos.

-

La forma segura y fácil de utilizar un generador de juego truco juntos

-

La forma legal de descargar juego hack juntos es utilizar un generador que es aprobado por los desarrolladores de juegos y las tiendas de aplicaciones. Este es un sitio web que le permite generar dinero ilimitado, diamantes y gemas para su cuenta en pocos minutos. Es seguro, fácil y gratuito. Estos son algunos de los beneficios de usar este método:

-
    -
  • No hay virus, malware o spyware en su dispositivo, ya que no tiene que descargar nada
  • -
  • No hay estafas o fraudes, ya que no tiene que proporcionar ninguna información personal o detalles de pago
  • -
  • No hay prohibiciones ni pérdidas de cuenta, ya que no infringe ningún término de servicio
  • -
-

Por lo tanto, recomendamos usar este método ya que es la mejor manera de obtener recursos ilimitados en Play Together.

-

Los pasos a seguir para obtener recursos ilimitados en su cuenta

-

Para utilizar el generador de hack play together, solo tiene que seguir estos sencillos pasos:

-
    - -
  1. Introduzca su nombre de usuario o dirección de correo electrónico que utiliza para jugar Play Together
  2. -
  3. Seleccione el tipo de dispositivo (Android o iOS) y haga clic en Conectar
  4. -
  5. Seleccione la cantidad de dinero, diamantes y gemas que desea generar y haga clic en Generar
  6. -
  7. Espere unos segundos mientras el generador procesa su solicitud
  8. -
  9. Complete un paso rápido de verificación humana para demostrar que no es un robot
  10. -
  11. Compruebe su cuenta y disfrute de sus recursos ilimitados!
  12. -
-

Conclusión

-

En conclusión, Play Together es un juego divertido y social donde puedes conocer amigos de todo el mundo, jugar minijuegos, personalizar tu personaje y casa, y criar mascotas. Sin embargo, si desea disfrutar del juego sin gastar dinero real, es posible que desee descargar hack jugar juntos y obtener dinero ilimitado, diamantes y gemas en su cuenta. La mejor manera de hacer eso es utilizar un juego hack junto generador que es seguro, fácil y libre de usar. Entonces, ¿qué estás esperando? Pruebe el juego hack juntos generador de hoy y ver por sí mismo lo divertido que es jugar Play Together con recursos ilimitados. Te sorprenderá lo mucho que puedes hacer y comprar en el juego. También podrás hacer más amigos y divertirte más con ellos. Solo recuerda usar el generador de forma responsable y no abusar de él. Además, sé respetuoso con otros jugadores y no arruines su experiencia de juego. Después de todo, Play Together es un juego que está destinado a reunir a la gente y pasar un buen rato.

-

Antes de ir, aquí hay algunas preguntas frecuentes que usted podría tener sobre el juego hack juntos:

-

Preguntas frecuentes

-

¿Es seguro jugar juntos?

- -

¿Cuánto tiempo se tarda en obtener los recursos en mi cuenta?

-

Por lo general, se tarda solo unos minutos para obtener los recursos en su cuenta después de usar el generador de juego hack juntos. Sin embargo, a veces puede tomar más tiempo dependiendo de la carga del servidor o el proceso de verificación. Si no ve los recursos en su cuenta después de 15 minutos, puede volver a intentarlo o ponerse en contacto con el equipo de soporte del generador para obtener ayuda.

-

¿Puedo usar hack jugar juntos en cualquier dispositivo?

-

Sí, se puede utilizar hack jugar juntos en cualquier dispositivo que puede ejecutar Jugar juntos. Esto incluye dispositivos Android e iOS, así como ordenadores PC y Mac. Solo tiene que tener una conexión a Internet estable y un navegador web para acceder al hack jugar juntos sitio web generador. No es necesario que raíz o jailbreak su dispositivo o instalar cualquier software o aplicación.

-

¿Me van a prohibir el uso de hack jugar juntos?

-

No, no se le prohibió el uso de hack jugar juntos, siempre y cuando se utiliza moderada y sabiamente. El generador de hack play together utiliza cifrado avanzado y servidores proxy para proteger su cuenta de detección y prohibición. Sin embargo, si lo usas con demasiada frecuencia o en exceso, podrías levantar sospechas de los desarrolladores de juegos u otros jugadores. Por lo tanto, ser inteligente y no exagerar.

-

¿Dónde puedo encontrar más información sobre el hack jugar juntos?

-

Si desea encontrar más información sobre el juego hack juntos, puede visitar el sitio web oficial del generador o seguir sus páginas de redes sociales. También puede leer comentarios y testimonios de otros usuarios que han utilizado el generador y ver cómo les gustó. También puede ponerse en contacto con el equipo de soporte del generador si tiene alguna pregunta o problema con el servicio.

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/packaging/requirements.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/packaging/requirements.py deleted file mode 100644 index 1eab7dd66d9bfdefea1a0e159303f1c09fa16d67..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/packaging/requirements.py +++ /dev/null @@ -1,146 +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. - -import re -import string -import urllib.parse -from typing import List, Optional as TOptional, Set - -from pip._vendor.pyparsing import ( # noqa - Combine, - Literal as L, - Optional, - ParseException, - Regex, - Word, - ZeroOrMore, - originalTextFor, - stringEnd, - stringStart, -) - -from .markers import MARKER_EXPR, Marker -from .specifiers import LegacySpecifier, Specifier, SpecifierSet - - -class InvalidRequirement(ValueError): - """ - An invalid requirement was found, users should refer to PEP 508. - """ - - -ALPHANUM = Word(string.ascii_letters + string.digits) - -LBRACKET = L("[").suppress() -RBRACKET = L("]").suppress() -LPAREN = L("(").suppress() -RPAREN = L(")").suppress() -COMMA = L(",").suppress() -SEMICOLON = L(";").suppress() -AT = L("@").suppress() - -PUNCTUATION = Word("-_.") -IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM) -IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END)) - -NAME = IDENTIFIER("name") -EXTRA = IDENTIFIER - -URI = Regex(r"[^ ]+")("url") -URL = AT + URI - -EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA) -EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras") - -VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE) -VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE) - -VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY -VERSION_MANY = Combine( - VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False -)("_raw_spec") -_VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY) -_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or "") - -VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier") -VERSION_SPEC.setParseAction(lambda s, l, t: t[1]) - -MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker") -MARKER_EXPR.setParseAction( - lambda s, l, t: Marker(s[t._original_start : t._original_end]) -) -MARKER_SEPARATOR = SEMICOLON -MARKER = MARKER_SEPARATOR + MARKER_EXPR - -VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER) -URL_AND_MARKER = URL + Optional(MARKER) - -NAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER) - -REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd -# pyparsing isn't thread safe during initialization, so we do it eagerly, see -# issue #104 -REQUIREMENT.parseString("x[]") - - -class Requirement: - """Parse a requirement. - - Parse a given requirement string into its parts, such as name, specifier, - URL, and extras. Raises InvalidRequirement on a badly-formed requirement - string. - """ - - # TODO: Can we test whether something is contained within a requirement? - # If so how do we do that? Do we need to test against the _name_ of - # the thing as well as the version? What about the markers? - # TODO: Can we normalize the name and extra name? - - def __init__(self, requirement_string: str) -> None: - try: - req = REQUIREMENT.parseString(requirement_string) - except ParseException as e: - raise InvalidRequirement( - f'Parse error at "{ requirement_string[e.loc : e.loc + 8]!r}": {e.msg}' - ) - - self.name: str = req.name - if req.url: - parsed_url = urllib.parse.urlparse(req.url) - if parsed_url.scheme == "file": - if urllib.parse.urlunparse(parsed_url) != req.url: - raise InvalidRequirement("Invalid URL given") - elif not (parsed_url.scheme and parsed_url.netloc) or ( - not parsed_url.scheme and not parsed_url.netloc - ): - raise InvalidRequirement(f"Invalid URL: {req.url}") - self.url: TOptional[str] = req.url - else: - self.url = None - self.extras: Set[str] = set(req.extras.asList() if req.extras else []) - self.specifier: SpecifierSet = SpecifierSet(req.specifier) - self.marker: TOptional[Marker] = req.marker if req.marker else None - - def __str__(self) -> str: - parts: List[str] = [self.name] - - if self.extras: - formatted_extras = ",".join(sorted(self.extras)) - parts.append(f"[{formatted_extras}]") - - if self.specifier: - parts.append(str(self.specifier)) - - if self.url: - parts.append(f"@ {self.url}") - if self.marker: - parts.append(" ") - - if self.marker: - parts.append(f"; {self.marker}") - - return "".join(parts) - - def __repr__(self) -> str: - return f"" diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/rule.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/rule.py deleted file mode 100644 index fd00ce6e4cea506f3ab08e6412d2eb6443ef582c..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/rule.py +++ /dev/null @@ -1,130 +0,0 @@ -from typing import Union - -from .align import AlignMethod -from .cells import cell_len, set_cell_size -from .console import Console, ConsoleOptions, RenderResult -from .jupyter import JupyterMixin -from .measure import Measurement -from .style import Style -from .text import Text - - -class Rule(JupyterMixin): - """A console renderable to draw a horizontal rule (line). - - Args: - title (Union[str, Text], optional): Text to render in the rule. Defaults to "". - characters (str, optional): Character(s) used to draw the line. Defaults to "─". - style (StyleType, optional): Style of Rule. Defaults to "rule.line". - end (str, optional): Character at end of Rule. defaults to "\\\\n" - align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". - """ - - def __init__( - self, - title: Union[str, Text] = "", - *, - characters: str = "─", - style: Union[str, Style] = "rule.line", - end: str = "\n", - align: AlignMethod = "center", - ) -> None: - if cell_len(characters) < 1: - raise ValueError( - "'characters' argument must have a cell width of at least 1" - ) - if align not in ("left", "center", "right"): - raise ValueError( - f'invalid value for align, expected "left", "center", "right" (not {align!r})' - ) - self.title = title - self.characters = characters - self.style = style - self.end = end - self.align = align - - def __repr__(self) -> str: - return f"Rule({self.title!r}, {self.characters!r})" - - def __rich_console__( - self, console: Console, options: ConsoleOptions - ) -> RenderResult: - width = options.max_width - - characters = ( - "-" - if (options.ascii_only and not self.characters.isascii()) - else self.characters - ) - - chars_len = cell_len(characters) - if not self.title: - yield self._rule_line(chars_len, width) - return - - if isinstance(self.title, Text): - title_text = self.title - else: - title_text = console.render_str(self.title, style="rule.text") - - title_text.plain = title_text.plain.replace("\n", " ") - title_text.expand_tabs() - - required_space = 4 if self.align == "center" else 2 - truncate_width = max(0, width - required_space) - if not truncate_width: - yield self._rule_line(chars_len, width) - return - - rule_text = Text(end=self.end) - if self.align == "center": - title_text.truncate(truncate_width, overflow="ellipsis") - side_width = (width - cell_len(title_text.plain)) // 2 - left = Text(characters * (side_width // chars_len + 1)) - left.truncate(side_width - 1) - right_length = width - cell_len(left.plain) - cell_len(title_text.plain) - right = Text(characters * (side_width // chars_len + 1)) - right.truncate(right_length) - rule_text.append(left.plain + " ", self.style) - rule_text.append(title_text) - rule_text.append(" " + right.plain, self.style) - elif self.align == "left": - title_text.truncate(truncate_width, overflow="ellipsis") - rule_text.append(title_text) - rule_text.append(" ") - rule_text.append(characters * (width - rule_text.cell_len), self.style) - elif self.align == "right": - title_text.truncate(truncate_width, overflow="ellipsis") - rule_text.append(characters * (width - title_text.cell_len - 1), self.style) - rule_text.append(" ") - rule_text.append(title_text) - - rule_text.plain = set_cell_size(rule_text.plain, width) - yield rule_text - - def _rule_line(self, chars_len: int, width: int) -> Text: - rule_text = Text(self.characters * ((width // chars_len) + 1), self.style) - rule_text.truncate(width) - rule_text.plain = set_cell_size(rule_text.plain, width) - return rule_text - - def __rich_measure__( - self, console: Console, options: ConsoleOptions - ) -> Measurement: - return Measurement(1, 1) - - -if __name__ == "__main__": # pragma: no cover - import sys - - from pip._vendor.rich.console import Console - - try: - text = sys.argv[1] - except IndexError: - text = "Hello, World" - console = Console() - console.print(Rule(title=text)) - - console = Console() - console.print(Rule("foo"), width=4) diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/traceback.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/traceback.py deleted file mode 100644 index c4ffe1f99e6dc9c0509459196cb68fa95e79048d..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/traceback.py +++ /dev/null @@ -1,756 +0,0 @@ -from __future__ import absolute_import - -import linecache -import os -import platform -import sys -from dataclasses import dataclass, field -from traceback import walk_tb -from types import ModuleType, TracebackType -from typing import ( - Any, - Callable, - Dict, - Iterable, - List, - Optional, - Sequence, - Tuple, - Type, - Union, -) - -from pip._vendor.pygments.lexers import guess_lexer_for_filename -from pip._vendor.pygments.token import Comment, Keyword, Name, Number, Operator, String -from pip._vendor.pygments.token import Text as TextToken -from pip._vendor.pygments.token import Token -from pip._vendor.pygments.util import ClassNotFound - -from . import pretty -from ._loop import loop_last -from .columns import Columns -from .console import Console, ConsoleOptions, ConsoleRenderable, RenderResult, group -from .constrain import Constrain -from .highlighter import RegexHighlighter, ReprHighlighter -from .panel import Panel -from .scope import render_scope -from .style import Style -from .syntax import Syntax -from .text import Text -from .theme import Theme - -WINDOWS = platform.system() == "Windows" - -LOCALS_MAX_LENGTH = 10 -LOCALS_MAX_STRING = 80 - - -def install( - *, - console: Optional[Console] = None, - width: Optional[int] = 100, - extra_lines: int = 3, - theme: Optional[str] = None, - word_wrap: bool = False, - show_locals: bool = False, - locals_max_length: int = LOCALS_MAX_LENGTH, - locals_max_string: int = LOCALS_MAX_STRING, - locals_hide_dunder: bool = True, - locals_hide_sunder: Optional[bool] = None, - indent_guides: bool = True, - suppress: Iterable[Union[str, ModuleType]] = (), - max_frames: int = 100, -) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]: - """Install a rich traceback handler. - - Once installed, any tracebacks will be printed with syntax highlighting and rich formatting. - - - Args: - console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance. - width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100. - extra_lines (int, optional): Extra lines of code. Defaults to 3. - theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick - a theme appropriate for the platform. - word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. - show_locals (bool, optional): Enable display of local variables. Defaults to False. - locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. - Defaults to 10. - locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. - locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. - locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. - indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True. - suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. - - Returns: - Callable: The previous exception handler that was replaced. - - """ - traceback_console = Console(stderr=True) if console is None else console - - locals_hide_sunder = ( - True - if (traceback_console.is_jupyter and locals_hide_sunder is None) - else locals_hide_sunder - ) - - def excepthook( - type_: Type[BaseException], - value: BaseException, - traceback: Optional[TracebackType], - ) -> None: - traceback_console.print( - Traceback.from_exception( - type_, - value, - traceback, - width=width, - extra_lines=extra_lines, - theme=theme, - word_wrap=word_wrap, - show_locals=show_locals, - locals_max_length=locals_max_length, - locals_max_string=locals_max_string, - locals_hide_dunder=locals_hide_dunder, - locals_hide_sunder=bool(locals_hide_sunder), - indent_guides=indent_guides, - suppress=suppress, - max_frames=max_frames, - ) - ) - - def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover - tb_data = {} # store information about showtraceback call - default_showtraceback = ip.showtraceback # keep reference of default traceback - - def ipy_show_traceback(*args: Any, **kwargs: Any) -> None: - """wrap the default ip.showtraceback to store info for ip._showtraceback""" - nonlocal tb_data - tb_data = kwargs - default_showtraceback(*args, **kwargs) - - def ipy_display_traceback( - *args: Any, is_syntax: bool = False, **kwargs: Any - ) -> None: - """Internally called traceback from ip._showtraceback""" - nonlocal tb_data - exc_tuple = ip._get_exc_info() - - # do not display trace on syntax error - tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2] - - # determine correct tb_offset - compiled = tb_data.get("running_compiled_code", False) - tb_offset = tb_data.get("tb_offset", 1 if compiled else 0) - # remove ipython internal frames from trace with tb_offset - for _ in range(tb_offset): - if tb is None: - break - tb = tb.tb_next - - excepthook(exc_tuple[0], exc_tuple[1], tb) - tb_data = {} # clear data upon usage - - # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work - # this is also what the ipython docs recommends to modify when subclassing InteractiveShell - ip._showtraceback = ipy_display_traceback - # add wrapper to capture tb_data - ip.showtraceback = ipy_show_traceback - ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback( - *args, is_syntax=True, **kwargs - ) - - try: # pragma: no cover - # if within ipython, use customized traceback - ip = get_ipython() # type: ignore[name-defined] - ipy_excepthook_closure(ip) - return sys.excepthook - except Exception: - # otherwise use default system hook - old_excepthook = sys.excepthook - sys.excepthook = excepthook - return old_excepthook - - -@dataclass -class Frame: - filename: str - lineno: int - name: str - line: str = "" - locals: Optional[Dict[str, pretty.Node]] = None - - -@dataclass -class _SyntaxError: - offset: int - filename: str - line: str - lineno: int - msg: str - - -@dataclass -class Stack: - exc_type: str - exc_value: str - syntax_error: Optional[_SyntaxError] = None - is_cause: bool = False - frames: List[Frame] = field(default_factory=list) - - -@dataclass -class Trace: - stacks: List[Stack] - - -class PathHighlighter(RegexHighlighter): - highlights = [r"(?P.*/)(?P.+)"] - - -class Traceback: - """A Console renderable that renders a traceback. - - Args: - trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses - the last exception. - width (Optional[int], optional): Number of characters used to traceback. Defaults to 100. - extra_lines (int, optional): Additional lines of code to render. Defaults to 3. - theme (str, optional): Override pygments theme used in traceback. - word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. - show_locals (bool, optional): Enable display of local variables. Defaults to False. - indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True. - locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. - Defaults to 10. - locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. - locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. - locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. - suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. - max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. - - """ - - LEXERS = { - "": "text", - ".py": "python", - ".pxd": "cython", - ".pyx": "cython", - ".pxi": "pyrex", - } - - def __init__( - self, - trace: Optional[Trace] = None, - *, - width: Optional[int] = 100, - extra_lines: int = 3, - theme: Optional[str] = None, - word_wrap: bool = False, - show_locals: bool = False, - locals_max_length: int = LOCALS_MAX_LENGTH, - locals_max_string: int = LOCALS_MAX_STRING, - locals_hide_dunder: bool = True, - locals_hide_sunder: bool = False, - indent_guides: bool = True, - suppress: Iterable[Union[str, ModuleType]] = (), - max_frames: int = 100, - ): - if trace is None: - exc_type, exc_value, traceback = sys.exc_info() - if exc_type is None or exc_value is None or traceback is None: - raise ValueError( - "Value for 'trace' required if not called in except: block" - ) - trace = self.extract( - exc_type, exc_value, traceback, show_locals=show_locals - ) - self.trace = trace - self.width = width - self.extra_lines = extra_lines - self.theme = Syntax.get_theme(theme or "ansi_dark") - self.word_wrap = word_wrap - self.show_locals = show_locals - self.indent_guides = indent_guides - self.locals_max_length = locals_max_length - self.locals_max_string = locals_max_string - self.locals_hide_dunder = locals_hide_dunder - self.locals_hide_sunder = locals_hide_sunder - - self.suppress: Sequence[str] = [] - for suppress_entity in suppress: - if not isinstance(suppress_entity, str): - assert ( - suppress_entity.__file__ is not None - ), f"{suppress_entity!r} must be a module with '__file__' attribute" - path = os.path.dirname(suppress_entity.__file__) - else: - path = suppress_entity - path = os.path.normpath(os.path.abspath(path)) - self.suppress.append(path) - self.max_frames = max(4, max_frames) if max_frames > 0 else 0 - - @classmethod - def from_exception( - cls, - exc_type: Type[Any], - exc_value: BaseException, - traceback: Optional[TracebackType], - *, - width: Optional[int] = 100, - extra_lines: int = 3, - theme: Optional[str] = None, - word_wrap: bool = False, - show_locals: bool = False, - locals_max_length: int = LOCALS_MAX_LENGTH, - locals_max_string: int = LOCALS_MAX_STRING, - locals_hide_dunder: bool = True, - locals_hide_sunder: bool = False, - indent_guides: bool = True, - suppress: Iterable[Union[str, ModuleType]] = (), - max_frames: int = 100, - ) -> "Traceback": - """Create a traceback from exception info - - Args: - exc_type (Type[BaseException]): Exception type. - exc_value (BaseException): Exception value. - traceback (TracebackType): Python Traceback object. - width (Optional[int], optional): Number of characters used to traceback. Defaults to 100. - extra_lines (int, optional): Additional lines of code to render. Defaults to 3. - theme (str, optional): Override pygments theme used in traceback. - word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. - show_locals (bool, optional): Enable display of local variables. Defaults to False. - indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True. - locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. - Defaults to 10. - locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. - locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. - locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. - suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. - max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. - - Returns: - Traceback: A Traceback instance that may be printed. - """ - rich_traceback = cls.extract( - exc_type, - exc_value, - traceback, - show_locals=show_locals, - locals_max_length=locals_max_length, - locals_max_string=locals_max_string, - locals_hide_dunder=locals_hide_dunder, - locals_hide_sunder=locals_hide_sunder, - ) - - return cls( - rich_traceback, - width=width, - extra_lines=extra_lines, - theme=theme, - word_wrap=word_wrap, - show_locals=show_locals, - indent_guides=indent_guides, - locals_max_length=locals_max_length, - locals_max_string=locals_max_string, - locals_hide_dunder=locals_hide_dunder, - locals_hide_sunder=locals_hide_sunder, - suppress=suppress, - max_frames=max_frames, - ) - - @classmethod - def extract( - cls, - exc_type: Type[BaseException], - exc_value: BaseException, - traceback: Optional[TracebackType], - *, - show_locals: bool = False, - locals_max_length: int = LOCALS_MAX_LENGTH, - locals_max_string: int = LOCALS_MAX_STRING, - locals_hide_dunder: bool = True, - locals_hide_sunder: bool = False, - ) -> Trace: - """Extract traceback information. - - Args: - exc_type (Type[BaseException]): Exception type. - exc_value (BaseException): Exception value. - traceback (TracebackType): Python Traceback object. - show_locals (bool, optional): Enable display of local variables. Defaults to False. - locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. - Defaults to 10. - locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. - locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True. - locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False. - - Returns: - Trace: A Trace instance which you can use to construct a `Traceback`. - """ - - stacks: List[Stack] = [] - is_cause = False - - from pip._vendor.rich import _IMPORT_CWD - - def safe_str(_object: Any) -> str: - """Don't allow exceptions from __str__ to propagate.""" - try: - return str(_object) - except Exception: - return "" - - while True: - stack = Stack( - exc_type=safe_str(exc_type.__name__), - exc_value=safe_str(exc_value), - is_cause=is_cause, - ) - - if isinstance(exc_value, SyntaxError): - stack.syntax_error = _SyntaxError( - offset=exc_value.offset or 0, - filename=exc_value.filename or "?", - lineno=exc_value.lineno or 0, - line=exc_value.text or "", - msg=exc_value.msg, - ) - - stacks.append(stack) - append = stack.frames.append - - def get_locals( - iter_locals: Iterable[Tuple[str, object]] - ) -> Iterable[Tuple[str, object]]: - """Extract locals from an iterator of key pairs.""" - if not (locals_hide_dunder or locals_hide_sunder): - yield from iter_locals - return - for key, value in iter_locals: - if locals_hide_dunder and key.startswith("__"): - continue - if locals_hide_sunder and key.startswith("_"): - continue - yield key, value - - for frame_summary, line_no in walk_tb(traceback): - filename = frame_summary.f_code.co_filename - if filename and not filename.startswith("<"): - if not os.path.isabs(filename): - filename = os.path.join(_IMPORT_CWD, filename) - if frame_summary.f_locals.get("_rich_traceback_omit", False): - continue - - frame = Frame( - filename=filename or "?", - lineno=line_no, - name=frame_summary.f_code.co_name, - locals={ - key: pretty.traverse( - value, - max_length=locals_max_length, - max_string=locals_max_string, - ) - for key, value in get_locals(frame_summary.f_locals.items()) - } - if show_locals - else None, - ) - append(frame) - if frame_summary.f_locals.get("_rich_traceback_guard", False): - del stack.frames[:] - - cause = getattr(exc_value, "__cause__", None) - if cause: - exc_type = cause.__class__ - exc_value = cause - # __traceback__ can be None, e.g. for exceptions raised by the - # 'multiprocessing' module - traceback = cause.__traceback__ - is_cause = True - continue - - cause = exc_value.__context__ - if cause and not getattr(exc_value, "__suppress_context__", False): - exc_type = cause.__class__ - exc_value = cause - traceback = cause.__traceback__ - is_cause = False - continue - # No cover, code is reached but coverage doesn't recognize it. - break # pragma: no cover - - trace = Trace(stacks=stacks) - return trace - - def __rich_console__( - self, console: Console, options: ConsoleOptions - ) -> RenderResult: - theme = self.theme - background_style = theme.get_background_style() - token_style = theme.get_style_for_token - - traceback_theme = Theme( - { - "pretty": token_style(TextToken), - "pygments.text": token_style(Token), - "pygments.string": token_style(String), - "pygments.function": token_style(Name.Function), - "pygments.number": token_style(Number), - "repr.indent": token_style(Comment) + Style(dim=True), - "repr.str": token_style(String), - "repr.brace": token_style(TextToken) + Style(bold=True), - "repr.number": token_style(Number), - "repr.bool_true": token_style(Keyword.Constant), - "repr.bool_false": token_style(Keyword.Constant), - "repr.none": token_style(Keyword.Constant), - "scope.border": token_style(String.Delimiter), - "scope.equals": token_style(Operator), - "scope.key": token_style(Name), - "scope.key.special": token_style(Name.Constant) + Style(dim=True), - }, - inherit=False, - ) - - highlighter = ReprHighlighter() - for last, stack in loop_last(reversed(self.trace.stacks)): - if stack.frames: - stack_renderable: ConsoleRenderable = Panel( - self._render_stack(stack), - title="[traceback.title]Traceback [dim](most recent call last)", - style=background_style, - border_style="traceback.border", - expand=True, - padding=(0, 1), - ) - stack_renderable = Constrain(stack_renderable, self.width) - with console.use_theme(traceback_theme): - yield stack_renderable - if stack.syntax_error is not None: - with console.use_theme(traceback_theme): - yield Constrain( - Panel( - self._render_syntax_error(stack.syntax_error), - style=background_style, - border_style="traceback.border.syntax_error", - expand=True, - padding=(0, 1), - width=self.width, - ), - self.width, - ) - yield Text.assemble( - (f"{stack.exc_type}: ", "traceback.exc_type"), - highlighter(stack.syntax_error.msg), - ) - elif stack.exc_value: - yield Text.assemble( - (f"{stack.exc_type}: ", "traceback.exc_type"), - highlighter(stack.exc_value), - ) - else: - yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type")) - - if not last: - if stack.is_cause: - yield Text.from_markup( - "\n[i]The above exception was the direct cause of the following exception:\n", - ) - else: - yield Text.from_markup( - "\n[i]During handling of the above exception, another exception occurred:\n", - ) - - @group() - def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult: - highlighter = ReprHighlighter() - path_highlighter = PathHighlighter() - if syntax_error.filename != "": - if os.path.exists(syntax_error.filename): - text = Text.assemble( - (f" {syntax_error.filename}", "pygments.string"), - (":", "pygments.text"), - (str(syntax_error.lineno), "pygments.number"), - style="pygments.text", - ) - yield path_highlighter(text) - syntax_error_text = highlighter(syntax_error.line.rstrip()) - syntax_error_text.no_wrap = True - offset = min(syntax_error.offset - 1, len(syntax_error_text)) - syntax_error_text.stylize("bold underline", offset, offset) - syntax_error_text += Text.from_markup( - "\n" + " " * offset + "[traceback.offset]▲[/]", - style="pygments.text", - ) - yield syntax_error_text - - @classmethod - def _guess_lexer(cls, filename: str, code: str) -> str: - ext = os.path.splitext(filename)[-1] - if not ext: - # No extension, look at first line to see if it is a hashbang - # Note, this is an educated guess and not a guarantee - # If it fails, the only downside is that the code is highlighted strangely - new_line_index = code.index("\n") - first_line = code[:new_line_index] if new_line_index != -1 else code - if first_line.startswith("#!") and "python" in first_line.lower(): - return "python" - try: - return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name - except ClassNotFound: - return "text" - - @group() - def _render_stack(self, stack: Stack) -> RenderResult: - path_highlighter = PathHighlighter() - theme = self.theme - - def read_code(filename: str) -> str: - """Read files, and cache results on filename. - - Args: - filename (str): Filename to read - - Returns: - str: Contents of file - """ - return "".join(linecache.getlines(filename)) - - def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]: - if frame.locals: - yield render_scope( - frame.locals, - title="locals", - indent_guides=self.indent_guides, - max_length=self.locals_max_length, - max_string=self.locals_max_string, - ) - - exclude_frames: Optional[range] = None - if self.max_frames != 0: - exclude_frames = range( - self.max_frames // 2, - len(stack.frames) - self.max_frames // 2, - ) - - excluded = False - for frame_index, frame in enumerate(stack.frames): - - if exclude_frames and frame_index in exclude_frames: - excluded = True - continue - - if excluded: - assert exclude_frames is not None - yield Text( - f"\n... {len(exclude_frames)} frames hidden ...", - justify="center", - style="traceback.error", - ) - excluded = False - - first = frame_index == 0 - frame_filename = frame.filename - suppressed = any(frame_filename.startswith(path) for path in self.suppress) - - if os.path.exists(frame.filename): - text = Text.assemble( - path_highlighter(Text(frame.filename, style="pygments.string")), - (":", "pygments.text"), - (str(frame.lineno), "pygments.number"), - " in ", - (frame.name, "pygments.function"), - style="pygments.text", - ) - else: - text = Text.assemble( - "in ", - (frame.name, "pygments.function"), - (":", "pygments.text"), - (str(frame.lineno), "pygments.number"), - style="pygments.text", - ) - if not frame.filename.startswith("<") and not first: - yield "" - yield text - if frame.filename.startswith("<"): - yield from render_locals(frame) - continue - if not suppressed: - try: - code = read_code(frame.filename) - if not code: - # code may be an empty string if the file doesn't exist, OR - # if the traceback filename is generated dynamically - continue - lexer_name = self._guess_lexer(frame.filename, code) - syntax = Syntax( - code, - lexer_name, - theme=theme, - line_numbers=True, - line_range=( - frame.lineno - self.extra_lines, - frame.lineno + self.extra_lines, - ), - highlight_lines={frame.lineno}, - word_wrap=self.word_wrap, - code_width=88, - indent_guides=self.indent_guides, - dedent=False, - ) - yield "" - except Exception as error: - yield Text.assemble( - (f"\n{error}", "traceback.error"), - ) - else: - yield ( - Columns( - [ - syntax, - *render_locals(frame), - ], - padding=1, - ) - if frame.locals - else syntax - ) - - -if __name__ == "__main__": # pragma: no cover - - from .console import Console - - console = Console() - import sys - - def bar(a: Any) -> None: # 这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑 - one = 1 - print(one / a) - - def foo(a: Any) -> None: - _rich_traceback_guard = True - zed = { - "characters": { - "Paul Atreides", - "Vladimir Harkonnen", - "Thufir Hawat", - "Duncan Idaho", - }, - "atomic_types": (None, False, True), - } - bar(a) - - def error() -> None: - - try: - try: - foo(0) - except: - slfkjsldkfj # type: ignore[name-defined] - except: - console.print_exception(show_locals=True) - - error() diff --git a/spaces/BlitzEsports/TextToImage/README.md b/spaces/BlitzEsports/TextToImage/README.md deleted file mode 100644 index 11f784bbb29b3700509906fe8f610709f2ee584b..0000000000000000000000000000000000000000 --- a/spaces/BlitzEsports/TextToImage/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: DALL·E mini -metaTitle: "DALL·E mini by craiyon.com on Hugging Face" -emoji: 🥑 -colorFrom: yellow -colorTo: green -sdk: static -pinned: True -license: apache-2.0 ---- diff --git a/spaces/BlitzKriegM/argilla/README.md b/spaces/BlitzKriegM/argilla/README.md deleted file mode 100644 index 3218af156c07c5e7ee03cfefbeb62384d899f656..0000000000000000000000000000000000000000 --- a/spaces/BlitzKriegM/argilla/README.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Argilla Space Template -emoji: 🏷️ -colorFrom: purple -colorTo: red -sdk: docker -app_port: 6900 -fullWidth: true -tags: -- argilla -duplicated_from: fka/awesome-chatgpt-prompts ---- - -This is the Argilla Space Template you can use to deploy and run your own instance of Argilla on the Hugging Face Hub, for labeling, fun, and active learning loops! - -Login with: - -user: argilla -password: 1234 \ No newline at end of file diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/evaluation/rotated_coco_evaluation.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/evaluation/rotated_coco_evaluation.py deleted file mode 100644 index db3c42bd3a5b413fe24ad477b69a521783816fd0..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/evaluation/rotated_coco_evaluation.py +++ /dev/null @@ -1,203 +0,0 @@ -import itertools -import json -import numpy as np -import os -import torch -from fvcore.common.file_io import PathManager -from pycocotools.cocoeval import COCOeval, maskUtils - -from detectron2.structures import BoxMode, RotatedBoxes, pairwise_iou_rotated - -from .coco_evaluation import COCOEvaluator - - -class RotatedCOCOeval(COCOeval): - @staticmethod - def is_rotated(box_list): - if type(box_list) == np.ndarray: - return box_list.shape[1] == 5 - elif type(box_list) == list: - if box_list == []: # cannot decide the box_dim - return False - return np.all( - np.array( - [ - (len(obj) == 5) and ((type(obj) == list) or (type(obj) == np.ndarray)) - for obj in box_list - ] - ) - ) - return False - - @staticmethod - def boxlist_to_tensor(boxlist, output_box_dim): - if type(boxlist) == np.ndarray: - box_tensor = torch.from_numpy(boxlist) - elif type(boxlist) == list: - if boxlist == []: - return torch.zeros((0, output_box_dim), dtype=torch.float32) - else: - box_tensor = torch.FloatTensor(boxlist) - else: - raise Exception("Unrecognized boxlist type") - - input_box_dim = box_tensor.shape[1] - if input_box_dim != output_box_dim: - if input_box_dim == 4 and output_box_dim == 5: - box_tensor = BoxMode.convert(box_tensor, BoxMode.XYWH_ABS, BoxMode.XYWHA_ABS) - else: - raise Exception( - "Unable to convert from {}-dim box to {}-dim box".format( - input_box_dim, output_box_dim - ) - ) - return box_tensor - - def compute_iou_dt_gt(self, dt, gt, is_crowd): - if self.is_rotated(dt) or self.is_rotated(gt): - # TODO: take is_crowd into consideration - assert all(c == 0 for c in is_crowd) - dt = RotatedBoxes(self.boxlist_to_tensor(dt, output_box_dim=5)) - gt = RotatedBoxes(self.boxlist_to_tensor(gt, output_box_dim=5)) - return pairwise_iou_rotated(dt, gt) - else: - # This is the same as the classical COCO evaluation - return maskUtils.iou(dt, gt, is_crowd) - - def computeIoU(self, imgId, catId): - p = self.params - if p.useCats: - gt = self._gts[imgId, catId] - dt = self._dts[imgId, catId] - else: - gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]] - dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]] - if len(gt) == 0 and len(dt) == 0: - return [] - inds = np.argsort([-d["score"] for d in dt], kind="mergesort") - dt = [dt[i] for i in inds] - if len(dt) > p.maxDets[-1]: - dt = dt[0 : p.maxDets[-1]] - - assert p.iouType == "bbox", "unsupported iouType for iou computation" - - g = [g["bbox"] for g in gt] - d = [d["bbox"] for d in dt] - - # compute iou between each dt and gt region - iscrowd = [int(o["iscrowd"]) for o in gt] - - # Note: this function is copied from cocoeval.py in cocoapi - # and the major difference is here. - ious = self.compute_iou_dt_gt(d, g, iscrowd) - return ious - - -class RotatedCOCOEvaluator(COCOEvaluator): - """ - Evaluate object proposal/instance detection outputs using COCO-like metrics and APIs, - with rotated boxes support. - Note: this uses IOU only and does not consider angle differences. - """ - - def process(self, inputs, outputs): - """ - Args: - inputs: the inputs to a COCO model (e.g., GeneralizedRCNN). - It is a list of dict. Each dict corresponds to an image and - contains keys like "height", "width", "file_name", "image_id". - outputs: the outputs of a COCO model. It is a list of dicts with key - "instances" that contains :class:`Instances`. - """ - for input, output in zip(inputs, outputs): - prediction = {"image_id": input["image_id"]} - - if "instances" in output: - instances = output["instances"].to(self._cpu_device) - - prediction["instances"] = self.instances_to_json(instances, input["image_id"]) - if "proposals" in output: - prediction["proposals"] = output["proposals"].to(self._cpu_device) - self._predictions.append(prediction) - - def instances_to_json(self, instances, img_id): - num_instance = len(instances) - if num_instance == 0: - return [] - - boxes = instances.pred_boxes.tensor.numpy() - if boxes.shape[1] == 4: - boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS) - boxes = boxes.tolist() - scores = instances.scores.tolist() - classes = instances.pred_classes.tolist() - - results = [] - for k in range(num_instance): - result = { - "image_id": img_id, - "category_id": classes[k], - "bbox": boxes[k], - "score": scores[k], - } - - results.append(result) - return results - - def _eval_predictions(self, tasks, predictions): - """ - Evaluate predictions on the given tasks. - 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])) - - # unmap the category ids for COCO - if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"): - reverse_id_mapping = { - v: k for k, v in self._metadata.thing_dataset_id_to_contiguous_id.items() - } - for result in coco_results: - result["category_id"] = reverse_id_mapping[result["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 ...") - for task in sorted(tasks): - assert task == "bbox", "Task {} is not supported".format(task) - coco_eval = ( - self._evaluate_predictions_on_coco(self._coco_api, coco_results) - 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 - - def _evaluate_predictions_on_coco(self, coco_gt, coco_results): - """ - Evaluate the coco results using COCOEval API. - """ - assert len(coco_results) > 0 - - coco_dt = coco_gt.loadRes(coco_results) - - # Only bbox is supported for now - coco_eval = RotatedCOCOeval(coco_gt, coco_dt, iouType="bbox") - - coco_eval.evaluate() - coco_eval.accumulate() - coco_eval.summarize() - - return coco_eval diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/datasets/gqa/gqa_loader.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/datasets/gqa/gqa_loader.py deleted file mode 100644 index ded8077dd6266b4f31676ac5da2ce26014629356..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/datasets/gqa/gqa_loader.py +++ /dev/null @@ -1,277 +0,0 @@ -# -------------------------------------------------------- -# OpenVQA -# Written by Yuhao Cui https://github.com/cuiyuhao1996 -# -------------------------------------------------------- - -import numpy as np -import glob, json, re, en_vectors_web_lg -from openvqa.core.base_dataset import BaseDataSet -from openvqa.utils.ans_punct import prep_ans - - -class DataSet(BaseDataSet): - def __init__(self, __C): - super(DataSet, self).__init__() - self.__C = __C - - # -------------------------- - # ---- Raw data loading ---- - # -------------------------- - - ques_dict_preread = { - 'train': json.load(open(__C.RAW_PATH[__C.DATASET]['train'], 'r')), - 'val': json.load(open(__C.RAW_PATH[__C.DATASET]['val'], 'r')), - 'testdev': json.load(open(__C.RAW_PATH[__C.DATASET]['testdev'], 'r')), - 'test': json.load(open(__C.RAW_PATH[__C.DATASET]['test'], 'r')), - } - - # Loading all image paths - frcn_feat_path_list = glob.glob(__C.FEATS_PATH[__C.DATASET]['default-frcn'] + '/*.npz') - grid_feat_path_list = glob.glob(__C.FEATS_PATH[__C.DATASET]['default-grid'] + '/*.npz') - - # Loading question word list - # stat_ques_dict = { - # **ques_dict_preread['train'], - # **ques_dict_preread['val'], - # **ques_dict_preread['testdev'], - # **ques_dict_preread['test'], - # } - - # Loading answer word list - # stat_ans_dict = { - # **ques_dict_preread['train'], - # **ques_dict_preread['val'], - # **ques_dict_preread['testdev'], - # } - - # Loading question and answer list - self.ques_dict = {} - split_list = __C.SPLIT[__C.RUN_MODE].split('+') - for split in split_list: - if split in ques_dict_preread: - self.ques_dict = { - **self.ques_dict, - **ques_dict_preread[split], - } - else: - self.ques_dict = { - **self.ques_dict, - **json.load(open(__C.RAW_PATH[__C.DATASET][split], 'r')), - } - - # Define run data size - self.data_size = self.ques_dict.__len__() - print(' ========== Dataset size:', self.data_size) - - - # ------------------------ - # ---- Data statistic ---- - # ------------------------ - - # {image id} -> {image feature absolutely path} - self.iid_to_frcn_feat_path = self.img_feat_path_load(frcn_feat_path_list) - self.iid_to_grid_feat_path = self.img_feat_path_load(grid_feat_path_list) - - # Loading dict: question dict -> question list - self.qid_list = list(self.ques_dict.keys()) - - # Tokenize - self.token_to_ix, self.pretrained_emb, max_token = self.tokenize('openvqa/datasets/gqa/dicts.json', __C.USE_GLOVE) - self.token_size = self.token_to_ix.__len__() - print(' ========== Question token vocab size:', self.token_size) - - self.max_token = -1 - if self.max_token == -1: - self.max_token = max_token - print('Max token length:', max_token, 'Trimmed to:', self.max_token) - - # Answers statistic - self.ans_to_ix, self.ix_to_ans = self.ans_stat('openvqa/datasets/gqa/dicts.json') - self.ans_size = self.ans_to_ix.__len__() - print(' ========== Answer token vocab size:', self.ans_size) - print('Finished!') - print('') - - - - def img_feat_path_load(self, path_list): - iid_to_path = {} - - for ix, path in enumerate(path_list): - iid = path.split('/')[-1].split('.')[0] - iid_to_path[iid] = path - - return iid_to_path - - - # def tokenize(self, stat_ques_dict, use_glove): - # token_to_ix = { - # 'PAD': 0, - # 'UNK': 1, - # 'CLS': 2, - # } - # - # spacy_tool = None - # pretrained_emb = [] - # if use_glove: - # spacy_tool = en_vectors_web_lg.load() - # pretrained_emb.append(spacy_tool('PAD').vector) - # pretrained_emb.append(spacy_tool('UNK').vector) - # pretrained_emb.append(spacy_tool('CLS').vector) - # - # max_token = 0 - # for qid in stat_ques_dict: - # ques = stat_ques_dict[qid]['question'] - # words = re.sub( - # r"([.,'!?\"()*#:;])", - # '', - # ques.lower() - # ).replace('-', ' ').replace('/', ' ').split() - # - # if len(words) > max_token: - # max_token = len(words) - # - # for word in words: - # if word not in token_to_ix: - # token_to_ix[word] = len(token_to_ix) - # if use_glove: - # pretrained_emb.append(spacy_tool(word).vector) - # - # pretrained_emb = np.array(pretrained_emb) - # - # return token_to_ix, pretrained_emb, max_token - # - # - # def ans_stat(self, stat_ans_dict): - # ans_to_ix = {} - # ix_to_ans = {} - # - # for qid in stat_ans_dict: - # ans = stat_ans_dict[qid]['answer'] - # ans = prep_ans(ans) - # - # if ans not in ans_to_ix: - # ix_to_ans[ans_to_ix.__len__()] = ans - # ans_to_ix[ans] = ans_to_ix.__len__() - # - # return ans_to_ix, ix_to_ans - - - def tokenize(self, json_file, use_glove): - token_to_ix, max_token = json.load(open(json_file, 'r'))[2:] - spacy_tool = None - if use_glove: - spacy_tool = en_vectors_web_lg.load() - - pretrained_emb = [] - for word in token_to_ix: - if use_glove: - pretrained_emb.append(spacy_tool(word).vector) - pretrained_emb = np.array(pretrained_emb) - - return token_to_ix, pretrained_emb, max_token - - - def ans_stat(self, json_file): - ans_to_ix, ix_to_ans = json.load(open(json_file, 'r'))[:2] - - return ans_to_ix, ix_to_ans - - - # ---------------------------------------------- - # ---- Real-Time Processing Implementations ---- - # ---------------------------------------------- - - def load_ques_ans(self, idx): - - qid = self.qid_list[idx] - iid = self.ques_dict[qid]['imageId'] - - ques = self.ques_dict[qid]['question'] - ques_ix_iter = self.proc_ques(ques, self.token_to_ix, max_token=self.max_token) - ans_iter = np.zeros(1) - - if self.__C.RUN_MODE in ['train']: - # process answers - ans = self.ques_dict[qid]['answer'] - ans_iter = self.proc_ans(ans, self.ans_to_ix) - - return ques_ix_iter, ans_iter, iid - - - def load_img_feats(self, idx, iid): - frcn_feat = np.load(self.iid_to_frcn_feat_path[iid]) - frcn_feat_iter = self.proc_img_feat(frcn_feat['x'], img_feat_pad_size=self.__C.FEAT_SIZE['gqa']['FRCN_FEAT_SIZE'][0]) - - grid_feat = np.load(self.iid_to_grid_feat_path[iid]) - grid_feat_iter = grid_feat['x'] - - bbox_feat_iter = self.proc_img_feat( - self.proc_bbox_feat( - frcn_feat['bbox'], - (frcn_feat['height'], frcn_feat['width']) - ), - img_feat_pad_size=self.__C.FEAT_SIZE['gqa']['BBOX_FEAT_SIZE'][0] - ) - - return frcn_feat_iter, grid_feat_iter, bbox_feat_iter - - - - # ------------------------------------ - # ---- Real-Time Processing Utils ---- - # ------------------------------------ - - def proc_img_feat(self, img_feat, img_feat_pad_size): - if img_feat.shape[0] > img_feat_pad_size: - img_feat = img_feat[:img_feat_pad_size] - - img_feat = np.pad( - img_feat, - ((0, img_feat_pad_size - img_feat.shape[0]), (0, 0)), - mode='constant', - constant_values=0 - ) - - return img_feat - - - def proc_bbox_feat(self, bbox, img_shape): - bbox_feat = np.zeros((bbox.shape[0], 5), dtype=np.float32) - - bbox_feat[:, 0] = bbox[:, 0] / float(img_shape[1]) - bbox_feat[:, 1] = bbox[:, 1] / float(img_shape[0]) - bbox_feat[:, 2] = bbox[:, 2] / float(img_shape[1]) - bbox_feat[:, 3] = bbox[:, 3] / float(img_shape[0]) - bbox_feat[:, 4] = (bbox[:, 2] - bbox[:, 0]) * (bbox[:, 3] - bbox[:, 1]) / float(img_shape[0] * img_shape[1]) - - return bbox_feat - - - def proc_ques(self, ques, token_to_ix, max_token): - ques_ix = np.zeros(max_token, np.int64) - - words = re.sub( - r"([.,'!?\"()*#:;])", - '', - ques.lower() - ).replace('-', ' ').replace('/', ' ').split() - - for ix, word in enumerate(words): - if word in token_to_ix: - ques_ix[ix] = token_to_ix[word] - else: - ques_ix[ix] = token_to_ix['UNK'] - - if ix + 1 == max_token: - break - - return ques_ix - - - def proc_ans(self, ans, ans_to_ix): - ans_ix = np.zeros(1, np.int64) - ans = prep_ans(ans) - ans_ix[0] = ans_to_ix[ans] - - return ans_ix diff --git a/spaces/CVPR/LIVE/pybind11/tests/test_numpy_dtypes.py b/spaces/CVPR/LIVE/pybind11/tests/test_numpy_dtypes.py deleted file mode 100644 index 417d6f1cffbbd3a08857797c5c22f555d6f2dd33..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/tests/test_numpy_dtypes.py +++ /dev/null @@ -1,312 +0,0 @@ -# -*- coding: utf-8 -*- -import re - -import pytest - -import env # noqa: F401 - -from pybind11_tests import numpy_dtypes as m - -np = pytest.importorskip("numpy") - - -@pytest.fixture(scope='module') -def simple_dtype(): - ld = np.dtype('longdouble') - return np.dtype({'names': ['bool_', 'uint_', 'float_', 'ldbl_'], - 'formats': ['?', 'u4', 'f4', 'f{}'.format(ld.itemsize)], - 'offsets': [0, 4, 8, (16 if ld.alignment > 4 else 12)]}) - - -@pytest.fixture(scope='module') -def packed_dtype(): - return np.dtype([('bool_', '?'), ('uint_', 'u4'), ('float_', 'f4'), ('ldbl_', 'g')]) - - -def dt_fmt(): - from sys import byteorder - e = '<' if byteorder == 'little' else '>' - return ("{{'names':['bool_','uint_','float_','ldbl_']," - " 'formats':['?','" + e + "u4','" + e + "f4','" + e + "f{}']," - " 'offsets':[0,4,8,{}], 'itemsize':{}}}") - - -def simple_dtype_fmt(): - ld = np.dtype('longdouble') - simple_ld_off = 12 + 4 * (ld.alignment > 4) - return dt_fmt().format(ld.itemsize, simple_ld_off, simple_ld_off + ld.itemsize) - - -def packed_dtype_fmt(): - from sys import byteorder - return "[('bool_', '?'), ('uint_', '{e}u4'), ('float_', '{e}f4'), ('ldbl_', '{e}f{}')]".format( - np.dtype('longdouble').itemsize, e='<' if byteorder == 'little' else '>') - - -def partial_ld_offset(): - return 12 + 4 * (np.dtype('uint64').alignment > 4) + 8 + 8 * ( - np.dtype('longdouble').alignment > 8) - - -def partial_dtype_fmt(): - ld = np.dtype('longdouble') - partial_ld_off = partial_ld_offset() - return dt_fmt().format(ld.itemsize, partial_ld_off, partial_ld_off + ld.itemsize) - - -def partial_nested_fmt(): - ld = np.dtype('longdouble') - partial_nested_off = 8 + 8 * (ld.alignment > 8) - partial_ld_off = partial_ld_offset() - partial_nested_size = partial_nested_off * 2 + partial_ld_off + ld.itemsize - return "{{'names':['a'], 'formats':[{}], 'offsets':[{}], 'itemsize':{}}}".format( - partial_dtype_fmt(), partial_nested_off, partial_nested_size) - - -def assert_equal(actual, expected_data, expected_dtype): - np.testing.assert_equal(actual, np.array(expected_data, dtype=expected_dtype)) - - -def test_format_descriptors(): - with pytest.raises(RuntimeError) as excinfo: - m.get_format_unbound() - assert re.match('^NumPy type info missing for .*UnboundStruct.*$', str(excinfo.value)) - - ld = np.dtype('longdouble') - ldbl_fmt = ('4x' if ld.alignment > 4 else '') + ld.char - ss_fmt = "^T{?:bool_:3xI:uint_:f:float_:" + ldbl_fmt + ":ldbl_:}" - dbl = np.dtype('double') - partial_fmt = ("^T{?:bool_:3xI:uint_:f:float_:" + - str(4 * (dbl.alignment > 4) + dbl.itemsize + 8 * (ld.alignment > 8)) + - "xg:ldbl_:}") - nested_extra = str(max(8, ld.alignment)) - assert m.print_format_descriptors() == [ - ss_fmt, - "^T{?:bool_:I:uint_:f:float_:g:ldbl_:}", - "^T{" + ss_fmt + ":a:^T{?:bool_:I:uint_:f:float_:g:ldbl_:}:b:}", - partial_fmt, - "^T{" + nested_extra + "x" + partial_fmt + ":a:" + nested_extra + "x}", - "^T{3s:a:3s:b:}", - "^T{(3)4s:a:(2)i:b:(3)B:c:1x(4, 2)f:d:}", - '^T{q:e1:B:e2:}', - '^T{Zf:cflt:Zd:cdbl:}' - ] - - -def test_dtype(simple_dtype): - from sys import byteorder - e = '<' if byteorder == 'little' else '>' - - assert m.print_dtypes() == [ - simple_dtype_fmt(), - packed_dtype_fmt(), - "[('a', {}), ('b', {})]".format(simple_dtype_fmt(), packed_dtype_fmt()), - partial_dtype_fmt(), - partial_nested_fmt(), - "[('a', 'S3'), ('b', 'S3')]", - ("{{'names':['a','b','c','d'], " + - "'formats':[('S4', (3,)),('" + e + "i4', (2,)),('u1', (3,)),('" + e + "f4', (4, 2))], " + - "'offsets':[0,12,20,24], 'itemsize':56}}").format(e=e), - "[('e1', '" + e + "i8'), ('e2', 'u1')]", - "[('x', 'i1'), ('y', '" + e + "u8')]", - "[('cflt', '" + e + "c8'), ('cdbl', '" + e + "c16')]" - ] - - d1 = np.dtype({'names': ['a', 'b'], 'formats': ['int32', 'float64'], - 'offsets': [1, 10], 'itemsize': 20}) - d2 = np.dtype([('a', 'i4'), ('b', 'f4')]) - assert m.test_dtype_ctors() == [np.dtype('int32'), np.dtype('float64'), - np.dtype('bool'), d1, d1, np.dtype('uint32'), d2] - - assert m.test_dtype_methods() == [np.dtype('int32'), simple_dtype, False, True, - np.dtype('int32').itemsize, simple_dtype.itemsize] - - assert m.trailing_padding_dtype() == m.buffer_to_dtype(np.zeros(1, m.trailing_padding_dtype())) - - -def test_recarray(simple_dtype, packed_dtype): - elements = [(False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)] - - for func, dtype in [(m.create_rec_simple, simple_dtype), (m.create_rec_packed, packed_dtype)]: - arr = func(0) - assert arr.dtype == dtype - assert_equal(arr, [], simple_dtype) - assert_equal(arr, [], packed_dtype) - - arr = func(3) - assert arr.dtype == dtype - assert_equal(arr, elements, simple_dtype) - assert_equal(arr, elements, packed_dtype) - - if dtype == simple_dtype: - assert m.print_rec_simple(arr) == [ - "s:0,0,0,-0", - "s:1,1,1.5,-2.5", - "s:0,2,3,-5" - ] - else: - assert m.print_rec_packed(arr) == [ - "p:0,0,0,-0", - "p:1,1,1.5,-2.5", - "p:0,2,3,-5" - ] - - nested_dtype = np.dtype([('a', simple_dtype), ('b', packed_dtype)]) - - arr = m.create_rec_nested(0) - assert arr.dtype == nested_dtype - assert_equal(arr, [], nested_dtype) - - arr = m.create_rec_nested(3) - assert arr.dtype == nested_dtype - assert_equal(arr, [((False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5)), - ((True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)), - ((False, 2, 3.0, -5.0), (True, 3, 4.5, -7.5))], nested_dtype) - assert m.print_rec_nested(arr) == [ - "n:a=s:0,0,0,-0;b=p:1,1,1.5,-2.5", - "n:a=s:1,1,1.5,-2.5;b=p:0,2,3,-5", - "n:a=s:0,2,3,-5;b=p:1,3,4.5,-7.5" - ] - - arr = m.create_rec_partial(3) - assert str(arr.dtype) == partial_dtype_fmt() - partial_dtype = arr.dtype - assert '' not in arr.dtype.fields - assert partial_dtype.itemsize > simple_dtype.itemsize - assert_equal(arr, elements, simple_dtype) - assert_equal(arr, elements, packed_dtype) - - arr = m.create_rec_partial_nested(3) - assert str(arr.dtype) == partial_nested_fmt() - assert '' not in arr.dtype.fields - assert '' not in arr.dtype.fields['a'][0].fields - assert arr.dtype.itemsize > partial_dtype.itemsize - np.testing.assert_equal(arr['a'], m.create_rec_partial(3)) - - -def test_array_constructors(): - data = np.arange(1, 7, dtype='int32') - for i in range(8): - np.testing.assert_array_equal(m.test_array_ctors(10 + i), data.reshape((3, 2))) - np.testing.assert_array_equal(m.test_array_ctors(20 + i), data.reshape((3, 2))) - for i in range(5): - np.testing.assert_array_equal(m.test_array_ctors(30 + i), data) - np.testing.assert_array_equal(m.test_array_ctors(40 + i), data) - - -def test_string_array(): - arr = m.create_string_array(True) - assert str(arr.dtype) == "[('a', 'S3'), ('b', 'S3')]" - assert m.print_string_array(arr) == [ - "a='',b=''", - "a='a',b='a'", - "a='ab',b='ab'", - "a='abc',b='abc'" - ] - dtype = arr.dtype - assert arr['a'].tolist() == [b'', b'a', b'ab', b'abc'] - assert arr['b'].tolist() == [b'', b'a', b'ab', b'abc'] - arr = m.create_string_array(False) - assert dtype == arr.dtype - - -def test_array_array(): - from sys import byteorder - e = '<' if byteorder == 'little' else '>' - - arr = m.create_array_array(3) - assert str(arr.dtype) == ( - "{{'names':['a','b','c','d'], " + - "'formats':[('S4', (3,)),('" + e + "i4', (2,)),('u1', (3,)),('{e}f4', (4, 2))], " + - "'offsets':[0,12,20,24], 'itemsize':56}}").format(e=e) - assert m.print_array_array(arr) == [ - "a={{A,B,C,D},{K,L,M,N},{U,V,W,X}},b={0,1}," + - "c={0,1,2},d={{0,1},{10,11},{20,21},{30,31}}", - "a={{W,X,Y,Z},{G,H,I,J},{Q,R,S,T}},b={1000,1001}," + - "c={10,11,12},d={{100,101},{110,111},{120,121},{130,131}}", - "a={{S,T,U,V},{C,D,E,F},{M,N,O,P}},b={2000,2001}," + - "c={20,21,22},d={{200,201},{210,211},{220,221},{230,231}}", - ] - assert arr['a'].tolist() == [[b'ABCD', b'KLMN', b'UVWX'], - [b'WXYZ', b'GHIJ', b'QRST'], - [b'STUV', b'CDEF', b'MNOP']] - assert arr['b'].tolist() == [[0, 1], [1000, 1001], [2000, 2001]] - assert m.create_array_array(0).dtype == arr.dtype - - -def test_enum_array(): - from sys import byteorder - e = '<' if byteorder == 'little' else '>' - - arr = m.create_enum_array(3) - dtype = arr.dtype - assert dtype == np.dtype([('e1', e + 'i8'), ('e2', 'u1')]) - assert m.print_enum_array(arr) == [ - "e1=A,e2=X", - "e1=B,e2=Y", - "e1=A,e2=X" - ] - assert arr['e1'].tolist() == [-1, 1, -1] - assert arr['e2'].tolist() == [1, 2, 1] - assert m.create_enum_array(0).dtype == dtype - - -def test_complex_array(): - from sys import byteorder - e = '<' if byteorder == 'little' else '>' - - arr = m.create_complex_array(3) - dtype = arr.dtype - assert dtype == np.dtype([('cflt', e + 'c8'), ('cdbl', e + 'c16')]) - assert m.print_complex_array(arr) == [ - "c:(0,0.25),(0.5,0.75)", - "c:(1,1.25),(1.5,1.75)", - "c:(2,2.25),(2.5,2.75)" - ] - assert arr['cflt'].tolist() == [0.0 + 0.25j, 1.0 + 1.25j, 2.0 + 2.25j] - assert arr['cdbl'].tolist() == [0.5 + 0.75j, 1.5 + 1.75j, 2.5 + 2.75j] - assert m.create_complex_array(0).dtype == dtype - - -def test_signature(doc): - assert doc(m.create_rec_nested) == \ - "create_rec_nested(arg0: int) -> numpy.ndarray[NestedStruct]" - - -def test_scalar_conversion(): - n = 3 - arrays = [m.create_rec_simple(n), m.create_rec_packed(n), - m.create_rec_nested(n), m.create_enum_array(n)] - funcs = [m.f_simple, m.f_packed, m.f_nested] - - for i, func in enumerate(funcs): - for j, arr in enumerate(arrays): - if i == j and i < 2: - assert [func(arr[k]) for k in range(n)] == [k * 10 for k in range(n)] - else: - with pytest.raises(TypeError) as excinfo: - func(arr[0]) - assert 'incompatible function arguments' in str(excinfo.value) - - -def test_register_dtype(): - with pytest.raises(RuntimeError) as excinfo: - m.register_dtype() - assert 'dtype is already registered' in str(excinfo.value) - - -@pytest.mark.xfail("env.PYPY") -def test_str_leak(): - from sys import getrefcount - fmt = "f4" - pytest.gc_collect() - start = getrefcount(fmt) - d = m.dtype_wrapper(fmt) - assert d is np.dtype("f4") - del d - pytest.gc_collect() - assert getrefcount(fmt) == start - - -def test_compare_buffer_info(): - assert all(m.compare_buffer_info()) diff --git a/spaces/CVPR/LIVE/thrust/thrust/cmake/FindTBB.cmake b/spaces/CVPR/LIVE/thrust/thrust/cmake/FindTBB.cmake deleted file mode 100644 index f0d5c8119b56036c23f930b6c7ea3f470f513d72..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/cmake/FindTBB.cmake +++ /dev/null @@ -1,440 +0,0 @@ -# - Find ThreadingBuildingBlocks include dirs and libraries -# Use this module by invoking find_package with the form: -# find_package(TBB -# [REQUIRED] # Fail with error if TBB is not found -# ) # -# Once done, this will define -# -# TBB_FOUND - system has TBB -# TBB_INCLUDE_DIRS - the TBB include directories -# TBB_LIBRARIES - TBB libraries to be lined, doesn't include malloc or -# malloc proxy -# TBB::tbb - imported target for the TBB library -# -# TBB_VERSION - Product Version Number ("MAJOR.MINOR") -# TBB_VERSION_MAJOR - Major Product Version Number -# TBB_VERSION_MINOR - Minor Product Version Number -# TBB_INTERFACE_VERSION - Engineering Focused Version Number -# TBB_COMPATIBLE_INTERFACE_VERSION - The oldest major interface version -# still supported. This uses the engineering -# focused interface version numbers. -# -# TBB_MALLOC_FOUND - system has TBB malloc library -# TBB_MALLOC_INCLUDE_DIRS - the TBB malloc include directories -# TBB_MALLOC_LIBRARIES - The TBB malloc libraries to be lined -# TBB::malloc - imported target for the TBB malloc library -# -# TBB_MALLOC_PROXY_FOUND - system has TBB malloc proxy library -# TBB_MALLOC_PROXY_INCLUDE_DIRS = the TBB malloc proxy include directories -# TBB_MALLOC_PROXY_LIBRARIES - The TBB malloc proxy libraries to be lined -# TBB::malloc_proxy - imported target for the TBB malloc proxy library -# -# -# This module reads hints about search locations from variables: -# ENV TBB_ARCH_PLATFORM - for eg. set it to "mic" for Xeon Phi builds -# ENV TBB_ROOT or just TBB_ROOT - root directory of tbb installation -# ENV TBB_BUILD_PREFIX - specifies the build prefix for user built tbb -# libraries. Should be specified with ENV TBB_ROOT -# and optionally... -# ENV TBB_BUILD_DIR - if build directory is different than ${TBB_ROOT}/build -# -# -# Modified by Robert Maynard from the original OGRE source -# -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- -# -#============================================================================= -# Copyright 2010-2012 Kitware, Inc. -# Copyright 2012 Rolf Eike Beer -# -# Distributed under the OSI-approved BSD License (the "License"); -# see accompanying file Copyright.txt for details. -# -# This software is distributed WITHOUT ANY WARRANTY; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the License for more information. -#============================================================================= -# (To distribute this file outside of CMake, substitute the full -# License text for the above reference.) - - -#============================================================================= -# FindTBB helper functions and macros -# - -#==================================================== -# Fix the library path in case it is a linker script -#==================================================== -function(tbb_extract_real_library library real_library) - if(NOT UNIX OR NOT EXISTS ${library}) - set(${real_library} "${library}" PARENT_SCOPE) - return() - endif() - - #Read in the first 4 bytes and see if they are the ELF magic number - set(_elf_magic "7f454c46") - file(READ ${library} _hex_data OFFSET 0 LIMIT 4 HEX) - if(_hex_data STREQUAL _elf_magic) - #we have opened a elf binary so this is what - #we should link to - set(${real_library} "${library}" PARENT_SCOPE) - return() - endif() - - file(READ ${library} _data OFFSET 0 LIMIT 1024) - if("${_data}" MATCHES "INPUT \\(([^(]+)\\)") - #extract out the .so name from REGEX MATCH command - set(_proper_so_name "${CMAKE_MATCH_1}") - - #construct path to the real .so which is presumed to be in the same directory - #as the input file - get_filename_component(_so_dir "${library}" DIRECTORY) - set(${real_library} "${_so_dir}/${_proper_so_name}" PARENT_SCOPE) - else() - #unable to determine what this library is so just hope everything works - #and pass it unmodified. - set(${real_library} "${library}" PARENT_SCOPE) - endif() -endfunction() - -#=============================================== -# Do the final processing for the package find. -#=============================================== -macro(findpkg_finish PREFIX TARGET_NAME) - if (${PREFIX}_INCLUDE_DIR AND ${PREFIX}_LIBRARY) - set(${PREFIX}_FOUND TRUE) - set (${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIR}) - set (${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARY}) - else () - if (${PREFIX}_FIND_REQUIRED) - message(FATAL_ERROR "Required library ${PREFIX} not found.") - elseif (NOT ${PREFIX}_FIND_QUIETLY) - message("Library ${PREFIX} not found.") - endif() - return() - endif () - - if (NOT TARGET "TBB::${TARGET_NAME}") - if (${PREFIX}_LIBRARY_RELEASE) - tbb_extract_real_library(${${PREFIX}_LIBRARY_RELEASE} real_release) - endif () - if (${PREFIX}_LIBRARY_DEBUG) - tbb_extract_real_library(${${PREFIX}_LIBRARY_DEBUG} real_debug) - endif () - add_library(TBB::${TARGET_NAME} UNKNOWN IMPORTED) - set_target_properties(TBB::${TARGET_NAME} PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${${PREFIX}_INCLUDE_DIR}") - if (${PREFIX}_LIBRARY_DEBUG AND ${PREFIX}_LIBRARY_RELEASE) - set_target_properties(TBB::${TARGET_NAME} PROPERTIES - IMPORTED_LOCATION "${real_release}" - IMPORTED_LOCATION_DEBUG "${real_debug}" - IMPORTED_LOCATION_RELEASE "${real_release}") - elseif (${PREFIX}_LIBRARY_RELEASE) - set_target_properties(TBB::${TARGET_NAME} PROPERTIES - IMPORTED_LOCATION "${real_release}") - elseif (${PREFIX}_LIBRARY_DEBUG) - set_target_properties(TBB::${TARGET_NAME} PROPERTIES - IMPORTED_LOCATION "${real_debug}") - endif () - endif () - - #mark the following variables as internal variables - mark_as_advanced(${PREFIX}_INCLUDE_DIR - ${PREFIX}_LIBRARY - ${PREFIX}_LIBRARY_DEBUG - ${PREFIX}_LIBRARY_RELEASE) -endmacro() - -#=============================================== -# Generate debug names from given release names -#=============================================== -macro(get_debug_names PREFIX) - foreach(i ${${PREFIX}}) - set(${PREFIX}_DEBUG ${${PREFIX}_DEBUG} ${i}d ${i}D ${i}_d ${i}_D ${i}_debug ${i}) - endforeach() -endmacro() - -#=============================================== -# See if we have env vars to help us find tbb -#=============================================== -macro(getenv_path VAR) - set(ENV_${VAR} $ENV{${VAR}}) - # replace won't work if var is blank - if (ENV_${VAR}) - string( REGEX REPLACE "\\\\" "/" ENV_${VAR} ${ENV_${VAR}} ) - endif () -endmacro() - -#=============================================== -# Couple a set of release AND debug libraries -#=============================================== -macro(make_library_set PREFIX) - if (${PREFIX}_RELEASE AND ${PREFIX}_DEBUG) - set(${PREFIX} optimized ${${PREFIX}_RELEASE} debug ${${PREFIX}_DEBUG}) - elseif (${PREFIX}_RELEASE) - set(${PREFIX} ${${PREFIX}_RELEASE}) - elseif (${PREFIX}_DEBUG) - set(${PREFIX} ${${PREFIX}_DEBUG}) - endif () -endmacro() - - -#============================================================================= -# Now to actually find TBB -# - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(TBB_ROOT) - -# initialize search paths -set(TBB_PREFIX_PATH ${TBB_ROOT} ${ENV_TBB_ROOT}) -set(TBB_INC_SEARCH_PATH "") -set(TBB_LIB_SEARCH_PATH "") - - -# If user built from sources -set(TBB_BUILD_PREFIX $ENV{TBB_BUILD_PREFIX}) -if (TBB_BUILD_PREFIX AND ENV_TBB_ROOT) - getenv_path(TBB_BUILD_DIR) - if (NOT ENV_TBB_BUILD_DIR) - set(ENV_TBB_BUILD_DIR ${ENV_TBB_ROOT}/build) - endif () - - # include directory under ${ENV_TBB_ROOT}/include - list(APPEND TBB_LIB_SEARCH_PATH - ${ENV_TBB_BUILD_DIR}/${TBB_BUILD_PREFIX}_release - ${ENV_TBB_BUILD_DIR}/${TBB_BUILD_PREFIX}_debug) -endif () - - -# For Windows, let's assume that the user might be using the precompiled -# TBB packages from the main website. These use a rather awkward directory -# structure (at least for automatically finding the right files) depending -# on platform and compiler, but we'll do our best to accommodate it. -# Not adding the same effort for the precompiled linux builds, though. Those -# have different versions for CC compiler versions and linux kernels which -# will never adequately match the user's setup, so there is no feasible way -# to detect the "best" version to use. The user will have to manually -# select the right files. (Chances are the distributions are shipping their -# custom version of tbb, anyway, so the problem is probably nonexistent.) -if (WIN32 AND MSVC) - set(COMPILER_PREFIX "vc7.1") - if (MSVC_VERSION EQUAL 1400) - set(COMPILER_PREFIX "vc8") - elseif(MSVC_VERSION EQUAL 1500) - set(COMPILER_PREFIX "vc9") - elseif(MSVC_VERSION EQUAL 1600) - set(COMPILER_PREFIX "vc10") - elseif(MSVC_VERSION EQUAL 1700) - set(COMPILER_PREFIX "vc11") - elseif(MSVC_VERSION EQUAL 1800) - set(COMPILER_PREFIX "vc12") - elseif(MSVC_VERSION GREATER_EQUAL 1900 AND MSVC_VERSION LESS_EQUAL 1925) - # 1900-1925 actually spans three Visual Studio versions: - # 1900 = VS 14.0 (v140 toolset) a.k.a. MSVC 2015 - # 1910-1919 = VS 15.0 (v141 toolset) a.k.a. MSVC 2017 - # 1920-1929 = VS 16.0 (v142 toolset) a.k.a. MSVC 2019 - # - # But these are binary compatible and TBB's open source distribution only - # ships a single vs14 lib (as of 2020.0) - set(COMPILER_PREFIX "vc14") - else() - # The next poor soul who finds themselves having to decode visual studio - # version conventions may find these helpful: - # - https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html - # - https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering - message(AUTHOR_WARNING - "Unrecognized MSVC version. Please update FindTBB.cmake. " - "Some TBB_* values may need to be set manually." - ) - endif () - - # for each prefix path, add ia32/64\${COMPILER_PREFIX}\lib to the lib search path - foreach (dir IN LISTS TBB_PREFIX_PATH) - if (CMAKE_CL_64) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/ia64/${COMPILER_PREFIX}/lib) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/ia64/${COMPILER_PREFIX}) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/intel64/${COMPILER_PREFIX}/lib) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/intel64/${COMPILER_PREFIX}) - else () - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/ia32/${COMPILER_PREFIX}/lib) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/ia32/${COMPILER_PREFIX}) - endif () - endforeach () -endif () - -# For OS X binary distribution, choose libc++ based libraries for Mavericks (10.9) -# and above and AppleClang -if (CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND - NOT CMAKE_SYSTEM_VERSION VERSION_LESS 13.0) - set (USE_LIBCXX OFF) - cmake_policy(GET CMP0025 POLICY_VAR) - - if (POLICY_VAR STREQUAL "NEW") - if (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") - set (USE_LIBCXX ON) - endif () - else () - if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - set (USE_LIBCXX ON) - endif () - endif () - - if (USE_LIBCXX) - foreach (dir IN LISTS TBB_PREFIX_PATH) - list (APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/libc++ ${dir}/libc++/lib) - endforeach () - endif () -endif () - -# check compiler ABI -if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - set(COMPILER_PREFIX) - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7) - list(APPEND COMPILER_PREFIX "gcc4.7") - endif() - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4) - list(APPEND COMPILER_PREFIX "gcc4.4") - endif() - list(APPEND COMPILER_PREFIX "gcc4.1") -elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(COMPILER_PREFIX) - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.6) - list(APPEND COMPILER_PREFIX "gcc4.7") - endif() - list(APPEND COMPILER_PREFIX "gcc4.4") -else() # Assume compatibility with 4.4 for other compilers - list(APPEND COMPILER_PREFIX "gcc4.4") -endif () - -# if platform architecture is explicitly specified -set(TBB_ARCH_PLATFORM $ENV{TBB_ARCH_PLATFORM}) -if (TBB_ARCH_PLATFORM) - foreach (dir IN LISTS TBB_PREFIX_PATH) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/${TBB_ARCH_PLATFORM}/lib) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/${TBB_ARCH_PLATFORM}) - endforeach () -endif () - -foreach (dir IN LISTS TBB_PREFIX_PATH) - foreach (prefix IN LISTS COMPILER_PREFIX) - if (CMAKE_SIZEOF_VOID_P EQUAL 8) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/intel64) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/intel64/${prefix}) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/intel64/lib) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/intel64/${prefix}/lib) - else () - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/ia32) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib/ia32/${prefix}) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/ia32/lib) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/ia32/${prefix}/lib) - endif () - endforeach() -endforeach () - -# add general search paths -foreach (dir IN LISTS TBB_PREFIX_PATH) - list(APPEND TBB_LIB_SEARCH_PATH ${dir}/lib ${dir}/Lib ${dir}/lib/tbb - ${dir}/Libs) - list(APPEND TBB_INC_SEARCH_PATH ${dir}/include ${dir}/Include - ${dir}/include/tbb) -endforeach () - -set(TBB_LIBRARY_NAMES tbb) -get_debug_names(TBB_LIBRARY_NAMES) - - -find_path(TBB_INCLUDE_DIR - NAMES tbb/tbb.h - PATHS ${TBB_INC_SEARCH_PATH}) - -find_library(TBB_LIBRARY_RELEASE - NAMES ${TBB_LIBRARY_NAMES} - PATHS ${TBB_LIB_SEARCH_PATH}) -find_library(TBB_LIBRARY_DEBUG - NAMES ${TBB_LIBRARY_NAMES_DEBUG} - PATHS ${TBB_LIB_SEARCH_PATH}) -make_library_set(TBB_LIBRARY) - -findpkg_finish(TBB tbb) - -#if we haven't found TBB no point on going any further -if (NOT TBB_FOUND) - return() -endif () - -#============================================================================= -# Look for TBB's malloc package -set(TBB_MALLOC_LIBRARY_NAMES tbbmalloc) -get_debug_names(TBB_MALLOC_LIBRARY_NAMES) - -find_path(TBB_MALLOC_INCLUDE_DIR - NAMES tbb/tbb.h - PATHS ${TBB_INC_SEARCH_PATH}) - -find_library(TBB_MALLOC_LIBRARY_RELEASE - NAMES ${TBB_MALLOC_LIBRARY_NAMES} - PATHS ${TBB_LIB_SEARCH_PATH}) -find_library(TBB_MALLOC_LIBRARY_DEBUG - NAMES ${TBB_MALLOC_LIBRARY_NAMES_DEBUG} - PATHS ${TBB_LIB_SEARCH_PATH}) -make_library_set(TBB_MALLOC_LIBRARY) - -findpkg_finish(TBB_MALLOC tbbmalloc) - -#============================================================================= -# Look for TBB's malloc proxy package -set(TBB_MALLOC_PROXY_LIBRARY_NAMES tbbmalloc_proxy) -get_debug_names(TBB_MALLOC_PROXY_LIBRARY_NAMES) - -find_path(TBB_MALLOC_PROXY_INCLUDE_DIR - NAMES tbb/tbbmalloc_proxy.h - PATHS ${TBB_INC_SEARCH_PATH}) - -find_library(TBB_MALLOC_PROXY_LIBRARY_RELEASE - NAMES ${TBB_MALLOC_PROXY_LIBRARY_NAMES} - PATHS ${TBB_LIB_SEARCH_PATH}) -find_library(TBB_MALLOC_PROXY_LIBRARY_DEBUG - NAMES ${TBB_MALLOC_PROXY_LIBRARY_NAMES_DEBUG} - PATHS ${TBB_LIB_SEARCH_PATH}) -make_library_set(TBB_MALLOC_PROXY_LIBRARY) - -findpkg_finish(TBB_MALLOC_PROXY tbbmalloc_proxy) - - -#============================================================================= -#parse all the version numbers from tbb -if(NOT TBB_VERSION) - - #only read the start of the file - file(STRINGS - "${TBB_INCLUDE_DIR}/tbb/tbb_stddef.h" - TBB_VERSION_CONTENTS - REGEX "VERSION") - - string(REGEX REPLACE - ".*#define TBB_VERSION_MAJOR ([0-9]+).*" "\\1" - TBB_VERSION_MAJOR "${TBB_VERSION_CONTENTS}") - - string(REGEX REPLACE - ".*#define TBB_VERSION_MINOR ([0-9]+).*" "\\1" - TBB_VERSION_MINOR "${TBB_VERSION_CONTENTS}") - - string(REGEX REPLACE - ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1" - TBB_INTERFACE_VERSION "${TBB_VERSION_CONTENTS}") - - string(REGEX REPLACE - ".*#define TBB_COMPATIBLE_INTERFACE_VERSION ([0-9]+).*" "\\1" - TBB_COMPATIBLE_INTERFACE_VERSION "${TBB_VERSION_CONTENTS}") - - set(TBB_VERSION "${TBB_VERSION_MAJOR}.${TBB_VERSION_MINOR}") - -endif() diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/tbb/detail/per_device_resource.h b/spaces/CVPR/LIVE/thrust/thrust/system/tbb/detail/per_device_resource.h deleted file mode 100644 index 1b8d61f92169e0e09c3821e59218f0dcbb70cbe5..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/tbb/detail/per_device_resource.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 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. - */ - -#pragma once - -#include - -// this system has no special per device resource functions - diff --git a/spaces/CVPR/ml-talking-face/client_rest.py b/spaces/CVPR/ml-talking-face/client_rest.py deleted file mode 100644 index 56531f337b13ffed8bb84dc1eb00d78a0b888837..0000000000000000000000000000000000000000 --- a/spaces/CVPR/ml-talking-face/client_rest.py +++ /dev/null @@ -1,74 +0,0 @@ -import requests -import json -import base64 -import argparse - -VIDEO_WIDTH = 1080 -VIDEO_HEIGHT = 1920 -SPEAKER_ID = 0 - -class RestAPIApplication: - def __init__(self, ip, port): - - if port < 0: - self.post_request_addr = f"http://{ip}/register/" - self.post_headers = {"Content-Type": "application/json"} - self.generate_addr = (lambda id_: f'http://{ip}/generate/{id_}') - else: - self.post_request_addr = f"http://{ip}:{port}/register/" - self.post_headers = {"Content-Type": "application/json"} - self.generate_addr = (lambda id_: f'http://{ip}:{port}/generate/{id_}') - - @staticmethod - def _get_json_request(text, lang, duration_rate, action, background_data=None, is_video_background=False): - request_form = dict() - - request_form['text'] = text - request_form['speaker'] = SPEAKER_ID - request_form['width'] = VIDEO_WIDTH - request_form['height'] = VIDEO_HEIGHT - - request_form['action'] = action - - if background_data is not None: - background_base64 = base64.b64encode(background_data).decode("UTF-8") - else: - background_base64 = "" - - request_form['background'] = background_base64 - request_form['durationRate'] = duration_rate - request_form['isVideoBackground'] = is_video_background - request_form['lang'] = lang - - request_as_json = json.dumps(request_form) - return request_as_json - - @staticmethod - def _get_video_id(results): - return json.loads(bytes.decode(results.content))['id'] - - def get_video(self, text, lang, duration_rate, action, background_data=None, is_video_background=False): - request_json = self._get_json_request(text, lang, duration_rate, action, background_data, is_video_background) - - # POST request with jsonified request - results = requests.post(self.post_request_addr, headers=self.post_headers, data=request_json) - - # GET video with the given id - video_id = self._get_video_id(results) - video_results = requests.get(self.generate_addr(video_id)) - - return video_results.content - - -def parse_args(): - parser = argparse.ArgumentParser( - description='REST API interface for talking face generation submitted to CVPR2022') - parser.add_argument('-i', '--ip', dest='rest_ip', type=str, default="127.0.0.1", help="IP for REST API") - parser.add_argument('-p', '--port', dest='rest_port', type=int, default=8080, help="Port for REST API") - args = parser.parse_args() - return args - - -if __name__ == '__main__': - args = parse_args() - rest_api_application = RestAPIApplication(args.rest_ip, args.rest_port) diff --git a/spaces/Caoyunkang/Segment-Any-Anomaly/SAM/segment_anything/modeling/prompt_encoder.py b/spaces/Caoyunkang/Segment-Any-Anomaly/SAM/segment_anything/modeling/prompt_encoder.py deleted file mode 100644 index c3143f4f8e02ddd7ca8587b40ff5d47c3a6b7ef3..0000000000000000000000000000000000000000 --- a/spaces/Caoyunkang/Segment-Any-Anomaly/SAM/segment_anything/modeling/prompt_encoder.py +++ /dev/null @@ -1,214 +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 numpy as np -import torch -from torch import nn - -from typing import Any, Optional, Tuple, Type - -from .common import LayerNorm2d - - -class PromptEncoder(nn.Module): - def __init__( - self, - embed_dim: int, - image_embedding_size: Tuple[int, int], - input_image_size: Tuple[int, int], - mask_in_chans: int, - activation: Type[nn.Module] = nn.GELU, - ) -> None: - """ - Encodes prompts for input to SAM's mask decoder. - - Arguments: - embed_dim (int): The prompts' embedding dimension - image_embedding_size (tuple(int, int)): The spatial size of the - image embedding, as (H, W). - input_image_size (int): The padded size of the image as input - to the image encoder, as (H, W). - mask_in_chans (int): The number of hidden channels used for - encoding input masks. - activation (nn.Module): The activation to use when encoding - input masks. - """ - super().__init__() - self.embed_dim = embed_dim - self.input_image_size = input_image_size - self.image_embedding_size = image_embedding_size - self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) - - self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners - point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] - self.point_embeddings = nn.ModuleList(point_embeddings) - self.not_a_point_embed = nn.Embedding(1, embed_dim) - - self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) - self.mask_downscaling = nn.Sequential( - nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), - LayerNorm2d(mask_in_chans // 4), - activation(), - nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), - LayerNorm2d(mask_in_chans), - activation(), - nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), - ) - self.no_mask_embed = nn.Embedding(1, embed_dim) - - def get_dense_pe(self) -> torch.Tensor: - """ - Returns the positional encoding used to encode point prompts, - applied to a dense set of points the shape of the image encoding. - - Returns: - torch.Tensor: Positional encoding with shape - 1x(embed_dim)x(embedding_h)x(embedding_w) - """ - return self.pe_layer(self.image_embedding_size).unsqueeze(0) - - def _embed_points( - self, - points: torch.Tensor, - labels: torch.Tensor, - pad: bool, - ) -> torch.Tensor: - """Embeds point prompts.""" - points = points + 0.5 # Shift to center of pixel - if pad: - padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) - padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) - points = torch.cat([points, padding_point], dim=1) - labels = torch.cat([labels, padding_label], dim=1) - point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) - point_embedding[labels == -1] = 0.0 - point_embedding[labels == -1] += self.not_a_point_embed.weight - point_embedding[labels == 0] += self.point_embeddings[0].weight - point_embedding[labels == 1] += self.point_embeddings[1].weight - return point_embedding - - def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: - """Embeds box prompts.""" - boxes = boxes + 0.5 # Shift to center of pixel - coords = boxes.reshape(-1, 2, 2) - corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) - corner_embedding[:, 0, :] += self.point_embeddings[2].weight - corner_embedding[:, 1, :] += self.point_embeddings[3].weight - return corner_embedding - - def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: - """Embeds mask inputs.""" - mask_embedding = self.mask_downscaling(masks) - return mask_embedding - - def _get_batch_size( - self, - points: Optional[Tuple[torch.Tensor, torch.Tensor]], - boxes: Optional[torch.Tensor], - masks: Optional[torch.Tensor], - ) -> int: - """ - Gets the batch size of the output given the batch size of the input prompts. - """ - if points is not None: - return points[0].shape[0] - elif boxes is not None: - return boxes.shape[0] - elif masks is not None: - return masks.shape[0] - else: - return 1 - - def _get_device(self) -> torch.device: - return self.point_embeddings[0].weight.device - - def forward( - self, - points: Optional[Tuple[torch.Tensor, torch.Tensor]], - boxes: Optional[torch.Tensor], - masks: Optional[torch.Tensor], - ) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Embeds different types of prompts, returning both sparse and dense - embeddings. - - Arguments: - points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates - and labels to embed. - boxes (torch.Tensor or none): boxes to embed - masks (torch.Tensor or none): masks to embed - - Returns: - torch.Tensor: sparse embeddings for the points and boxes, with shape - BxNx(embed_dim), where N is determined by the number of input points - and boxes. - torch.Tensor: dense embeddings for the masks, in the shape - Bx(embed_dim)x(embed_H)x(embed_W) - """ - bs = self._get_batch_size(points, boxes, masks) - sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) - if points is not None: - coords, labels = points - point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) - sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) - if boxes is not None: - box_embeddings = self._embed_boxes(boxes) - sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) - - if masks is not None: - dense_embeddings = self._embed_masks(masks) - else: - dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( - bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] - ) - - return sparse_embeddings, dense_embeddings - - -class PositionEmbeddingRandom(nn.Module): - """ - Positional encoding using random spatial frequencies. - """ - - def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: - super().__init__() - if scale is None or scale <= 0.0: - scale = 1.0 - self.register_buffer( - "positional_encoding_gaussian_matrix", - scale * torch.randn((2, num_pos_feats)), - ) - - def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: - """Positionally encode points that are normalized to [0,1].""" - # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape - coords = 2 * coords - 1 - coords = coords @ self.positional_encoding_gaussian_matrix - coords = 2 * np.pi * coords - # outputs d_1 x ... x d_n x C shape - return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) - - def forward(self, size: Tuple[int, int]) -> torch.Tensor: - """Generate positional encoding for a grid of the specified size.""" - h, w = size - device: Any = self.positional_encoding_gaussian_matrix.device - grid = torch.ones((h, w), device=device, dtype=torch.float32) - y_embed = grid.cumsum(dim=0) - 0.5 - x_embed = grid.cumsum(dim=1) - 0.5 - y_embed = y_embed / h - x_embed = x_embed / w - - pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) - return pe.permute(2, 0, 1) # C x H x W - - def forward_with_coords( - self, coords_input: torch.Tensor, image_size: Tuple[int, int] - ) -> torch.Tensor: - """Positionally encode points that are not normalized to [0,1].""" - coords = coords_input.clone() - coords[:, :, 0] = coords[:, :, 0] / image_size[1] - coords[:, :, 1] = coords[:, :, 1] / image_size[0] - return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/spaces/ChandraMohanNayal/AutoGPT/autogpt/agent/agent.py b/spaces/ChandraMohanNayal/AutoGPT/autogpt/agent/agent.py deleted file mode 100644 index ee7885f8844022597321fa6b492430ec34c0d6b9..0000000000000000000000000000000000000000 --- a/spaces/ChandraMohanNayal/AutoGPT/autogpt/agent/agent.py +++ /dev/null @@ -1,197 +0,0 @@ -from colorama import Fore, Style - -from autogpt.app import execute_command, get_command -from autogpt.chat import chat_with_ai, create_chat_message -from autogpt.config import Config -from autogpt.json_utils.json_fix_llm import fix_json_using_multiple_techniques -from autogpt.json_utils.utilities import validate_json -from autogpt.logs import logger, print_assistant_thoughts -from autogpt.speech import say_text -from autogpt.spinner import Spinner -from autogpt.utils import clean_input - - -class Agent: - """Agent class for interacting with Auto-GPT. - - Attributes: - ai_name: The name of the agent. - memory: The memory object to use. - full_message_history: The full message history. - next_action_count: The number of actions to execute. - system_prompt: The system prompt is the initial prompt that defines everything the AI needs to know to achieve its task successfully. - Currently, the dynamic and customizable information in the system prompt are ai_name, description and goals. - - triggering_prompt: The last sentence the AI will see before answering. For Auto-GPT, this prompt is: - Determine which next command to use, and respond using the format specified above: - The triggering prompt is not part of the system prompt because between the system prompt and the triggering - prompt we have contextual information that can distract the AI and make it forget that its goal is to find the next task to achieve. - SYSTEM PROMPT - CONTEXTUAL INFORMATION (memory, previous conversations, anything relevant) - TRIGGERING PROMPT - - The triggering prompt reminds the AI about its short term meta task (defining the next task) - """ - - def __init__( - self, - ai_name, - memory, - full_message_history, - next_action_count, - system_prompt, - triggering_prompt, - ): - self.ai_name = ai_name - self.memory = memory - self.full_message_history = full_message_history - self.next_action_count = next_action_count - self.system_prompt = system_prompt - self.triggering_prompt = triggering_prompt - - def start_interaction_loop(self): - # Interaction Loop - cfg = Config() - loop_count = 0 - command_name = None - arguments = None - user_input = "" - - while True: - # Discontinue if continuous limit is reached - loop_count += 1 - if ( - cfg.continuous_mode - and cfg.continuous_limit > 0 - and loop_count > cfg.continuous_limit - ): - logger.typewriter_log( - "Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}" - ) - break - - # Send message to AI, get response - with Spinner("Thinking... "): - assistant_reply = chat_with_ai( - self.system_prompt, - self.triggering_prompt, - self.full_message_history, - self.memory, - cfg.fast_token_limit, - ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument - - assistant_reply_json = fix_json_using_multiple_techniques(assistant_reply) - - # Print Assistant thoughts - if assistant_reply_json != {}: - validate_json(assistant_reply_json, "llm_response_format_1") - # Get command name and arguments - try: - print_assistant_thoughts(self.ai_name, assistant_reply_json) - command_name, arguments = get_command(assistant_reply_json) - # command_name, arguments = assistant_reply_json_valid["command"]["name"], assistant_reply_json_valid["command"]["args"] - if cfg.speak_mode: - say_text(f"I want to execute {command_name}") - except Exception as e: - logger.error("Error: \n", str(e)) - - if not cfg.continuous_mode and self.next_action_count == 0: - ### GET USER AUTHORIZATION TO EXECUTE COMMAND ### - # Get key press: Prompt the user to press enter to continue or escape - # to exit - logger.typewriter_log( - "NEXT ACTION: ", - Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} " - f"ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", - ) - print( - "Enter 'y' to authorise command, 'y -N' to run N continuous " - "commands, 'n' to exit program, or enter feedback for " - f"{self.ai_name}...", - flush=True, - ) - while True: - console_input = clean_input( - Fore.MAGENTA + "Input:" + Style.RESET_ALL - ) - if console_input.lower().strip() == "y": - user_input = "GENERATE NEXT COMMAND JSON" - break - elif console_input.lower().strip() == "": - print("Invalid input format.") - continue - elif console_input.lower().startswith("y -"): - try: - self.next_action_count = abs( - int(console_input.split(" ")[1]) - ) - user_input = "GENERATE NEXT COMMAND JSON" - except ValueError: - print( - "Invalid input format. Please enter 'y -n' where n is" - " the number of continuous tasks." - ) - continue - break - elif console_input.lower() == "n": - user_input = "EXIT" - break - else: - user_input = console_input - command_name = "human_feedback" - break - - if user_input == "GENERATE NEXT COMMAND JSON": - logger.typewriter_log( - "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=", - Fore.MAGENTA, - "", - ) - elif user_input == "EXIT": - print("Exiting...", flush=True) - break - else: - # Print command - logger.typewriter_log( - "NEXT ACTION: ", - Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}" - f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", - ) - - # Execute command - if command_name is not None and command_name.lower().startswith("error"): - result = ( - f"Command {command_name} threw the following error: {arguments}" - ) - elif command_name == "human_feedback": - result = f"Human feedback: {user_input}" - else: - result = ( - f"Command {command_name} returned: " - f"{execute_command(command_name, arguments)}" - ) - if self.next_action_count > 0: - self.next_action_count -= 1 - - memory_to_add = ( - f"Assistant Reply: {assistant_reply} " - f"\nResult: {result} " - f"\nHuman Feedback: {user_input} " - ) - - self.memory.add(memory_to_add) - - # Check if there's a result from the command append it to the message - # history - if result is not None: - self.full_message_history.append(create_chat_message("system", result)) - logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) - else: - self.full_message_history.append( - create_chat_message("system", "Unable to execute command") - ) - logger.typewriter_log( - "SYSTEM: ", Fore.YELLOW, "Unable to execute command" - ) diff --git a/spaces/CikeyQI/meme-api/meme_generator/memes/decent_kiss/__init__.py b/spaces/CikeyQI/meme-api/meme_generator/memes/decent_kiss/__init__.py deleted file mode 100644 index d08423bcd0a1197f3439882b022dfe2ba61eebf1..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/meme-api/meme_generator/memes/decent_kiss/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -from pathlib import Path -from typing import List - -from pil_utils import BuildImage - -from meme_generator import add_meme - -img_dir = Path(__file__).parent / "images" - - -def decent_kiss(images: List[BuildImage], texts, args): - img = images[0].convert("RGBA").resize((589, 340), keep_ratio=True) - frame = BuildImage.open(img_dir / "0.png") - frame.paste(img, (0, 91), below=True) - return frame.save_jpg() - - -add_meme("decent_kiss", decent_kiss, min_images=1, max_images=1, keywords=["像样的亲亲"]) diff --git a/spaces/Cong723/gpt-academic-public/crazy_functions/test_project/cpp/cppipc/prod_cons.h b/spaces/Cong723/gpt-academic-public/crazy_functions/test_project/cpp/cppipc/prod_cons.h deleted file mode 100644 index c9004bb8043a12e32814436baa6262a00c8ef68e..0000000000000000000000000000000000000000 --- a/spaces/Cong723/gpt-academic-public/crazy_functions/test_project/cpp/cppipc/prod_cons.h +++ /dev/null @@ -1,433 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "libipc/def.h" - -#include "libipc/platform/detail.h" -#include "libipc/circ/elem_def.h" -#include "libipc/utility/log.h" -#include "libipc/utility/utility.h" - -namespace ipc { - -//////////////////////////////////////////////////////////////// -/// producer-consumer implementation -//////////////////////////////////////////////////////////////// - -template -struct prod_cons_impl; - -template <> -struct prod_cons_impl> { - - template - struct elem_t { - std::aligned_storage_t data_ {}; - }; - - alignas(cache_line_size) std::atomic rd_; // read index - alignas(cache_line_size) std::atomic wt_; // write index - - constexpr circ::u2_t cursor() const noexcept { - return 0; - } - - template - bool push(W* /*wrapper*/, F&& f, E* elems) { - auto cur_wt = circ::index_of(wt_.load(std::memory_order_relaxed)); - if (cur_wt == circ::index_of(rd_.load(std::memory_order_acquire) - 1)) { - return false; // full - } - std::forward(f)(&(elems[cur_wt].data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - /** - * In single-single-unicast, 'force_push' means 'no reader' or 'the only one reader is dead'. - * So we could just disconnect all connections of receiver, and return false. - */ - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(~static_cast(0u)); - return false; - } - - template - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - auto cur_rd = circ::index_of(rd_.load(std::memory_order_relaxed)); - if (cur_rd == circ::index_of(wt_.load(std::memory_order_acquire))) { - return false; // empty - } - std::forward(f)(&(elems[cur_rd].data_)); - std::forward(out)(true); - rd_.fetch_add(1, std::memory_order_release); - return true; - } -}; - -template <> -struct prod_cons_impl> - : prod_cons_impl> { - - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(1); - return false; - } - - template class E, std::size_t DS, std::size_t AS> - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - byte_t buff[DS]; - for (unsigned k = 0;;) { - auto cur_rd = rd_.load(std::memory_order_relaxed); - if (circ::index_of(cur_rd) == - circ::index_of(wt_.load(std::memory_order_acquire))) { - return false; // empty - } - std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff)); - if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) { - std::forward(f)(buff); - std::forward(out)(true); - return true; - } - ipc::yield(k); - } - } -}; - -template <> -struct prod_cons_impl> - : prod_cons_impl> { - - using flag_t = std::uint64_t; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic f_ct_ { 0 }; // commit flag - }; - - alignas(cache_line_size) std::atomic ct_; // commit index - - template - bool push(W* /*wrapper*/, F&& f, E* elems) { - circ::u2_t cur_ct, nxt_ct; - for (unsigned k = 0;;) { - cur_ct = ct_.load(std::memory_order_relaxed); - if (circ::index_of(nxt_ct = cur_ct + 1) == - circ::index_of(rd_.load(std::memory_order_acquire))) { - return false; // full - } - if (ct_.compare_exchange_weak(cur_ct, nxt_ct, std::memory_order_acq_rel)) { - break; - } - ipc::yield(k); - } - auto* el = elems + circ::index_of(cur_ct); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - while (1) { - auto cac_ct = el->f_ct_.load(std::memory_order_acquire); - if (cur_ct != wt_.load(std::memory_order_relaxed)) { - return true; - } - if ((~cac_ct) != cur_ct) { - return true; - } - if (!el->f_ct_.compare_exchange_strong(cac_ct, 0, std::memory_order_relaxed)) { - return true; - } - wt_.store(nxt_ct, std::memory_order_release); - cur_ct = nxt_ct; - nxt_ct = cur_ct + 1; - el = elems + circ::index_of(cur_ct); - } - return true; - } - - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(1); - return false; - } - - template class E, std::size_t DS, std::size_t AS> - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - byte_t buff[DS]; - for (unsigned k = 0;;) { - auto cur_rd = rd_.load(std::memory_order_relaxed); - auto cur_wt = wt_.load(std::memory_order_acquire); - auto id_rd = circ::index_of(cur_rd); - auto id_wt = circ::index_of(cur_wt); - if (id_rd == id_wt) { - auto* el = elems + id_wt; - auto cac_ct = el->f_ct_.load(std::memory_order_acquire); - if ((~cac_ct) != cur_wt) { - return false; // empty - } - if (el->f_ct_.compare_exchange_weak(cac_ct, 0, std::memory_order_relaxed)) { - wt_.store(cur_wt + 1, std::memory_order_release); - } - k = 0; - } - else { - std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff)); - if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) { - std::forward(f)(buff); - std::forward(out)(true); - return true; - } - ipc::yield(k); - } - } - } -}; - -template <> -struct prod_cons_impl> { - - using rc_t = std::uint64_t; - - enum : rc_t { - ep_mask = 0x00000000ffffffffull, - ep_incr = 0x0000000100000000ull - }; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic rc_ { 0 }; // read-counter - }; - - alignas(cache_line_size) std::atomic wt_; // write index - alignas(cache_line_size) rc_t epoch_ { 0 }; // only one writer - - circ::u2_t cursor() const noexcept { - return wt_.load(std::memory_order_acquire); - } - - template - bool push(W* wrapper, F&& f, E* elems) { - E* el; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(wt_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & ep_mask; - if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch_)) { - return false; // has not finished yet - } - // consider rem_cc to be 0 here - if (el->rc_.compare_exchange_weak( - cur_rc, epoch_ | static_cast(cc), std::memory_order_release)) { - break; - } - ipc::yield(k); - } - std::forward(f)(&(el->data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - template - bool force_push(W* wrapper, F&& f, E* elems) { - E* el; - epoch_ += ep_incr; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(wt_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & ep_mask; - if (cc & rem_cc) { - ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc); - cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers - if (cc == 0) return false; // no reader - } - // just compare & exchange - if (el->rc_.compare_exchange_weak( - cur_rc, epoch_ | static_cast(cc), std::memory_order_release)) { - break; - } - ipc::yield(k); - } - std::forward(f)(&(el->data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - template - bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E* elems) { - if (cur == cursor()) return false; // acquire - auto* el = elems + circ::index_of(cur++); - std::forward(f)(&(el->data_)); - for (unsigned k = 0;;) { - auto cur_rc = el->rc_.load(std::memory_order_acquire); - if ((cur_rc & ep_mask) == 0) { - std::forward(out)(true); - return true; - } - auto nxt_rc = cur_rc & ~static_cast(wrapper->connected_id()); - if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) { - std::forward(out)((nxt_rc & ep_mask) == 0); - return true; - } - ipc::yield(k); - } - } -}; - -template <> -struct prod_cons_impl> { - - using rc_t = std::uint64_t; - using flag_t = std::uint64_t; - - enum : rc_t { - rc_mask = 0x00000000ffffffffull, - ep_mask = 0x00ffffffffffffffull, - ep_incr = 0x0100000000000000ull, - ic_mask = 0xff000000ffffffffull, - ic_incr = 0x0000000100000000ull - }; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic rc_ { 0 }; // read-counter - std::atomic f_ct_ { 0 }; // commit flag - }; - - alignas(cache_line_size) std::atomic ct_; // commit index - alignas(cache_line_size) std::atomic epoch_ { 0 }; - - circ::u2_t cursor() const noexcept { - return ct_.load(std::memory_order_acquire); - } - - constexpr static rc_t inc_rc(rc_t rc) noexcept { - return (rc & ic_mask) | ((rc + ic_incr) & ~ic_mask); - } - - constexpr static rc_t inc_mask(rc_t rc) noexcept { - return inc_rc(rc) & ~rc_mask; - } - - template - bool push(W* wrapper, F&& f, E* elems) { - E* el; - circ::u2_t cur_ct; - rc_t epoch = epoch_.load(std::memory_order_acquire); - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_relaxed); - circ::cc_t rem_cc = cur_rc & rc_mask; - if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch)) { - return false; // has not finished yet - } - else if (!rem_cc) { - auto cur_fl = el->f_ct_.load(std::memory_order_acquire); - if ((cur_fl != cur_ct) && cur_fl) { - return false; // full - } - } - // consider rem_cc to be 0 here - if (el->rc_.compare_exchange_weak( - cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast(cc), std::memory_order_relaxed) && - epoch_.compare_exchange_weak(epoch, epoch, std::memory_order_acq_rel)) { - break; - } - ipc::yield(k); - } - // only one thread/process would touch here at one time - ct_.store(cur_ct + 1, std::memory_order_release); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - return true; - } - - template - bool force_push(W* wrapper, F&& f, E* elems) { - E* el; - circ::u2_t cur_ct; - rc_t epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & rc_mask; - if (cc & rem_cc) { - ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc); - cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers - if (cc == 0) return false; // no reader - } - // just compare & exchange - if (el->rc_.compare_exchange_weak( - cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast(cc), std::memory_order_relaxed)) { - if (epoch == epoch_.load(std::memory_order_acquire)) { - break; - } - else if (push(wrapper, std::forward(f), elems)) { - return true; - } - epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr; - } - ipc::yield(k); - } - // only one thread/process would touch here at one time - ct_.store(cur_ct + 1, std::memory_order_release); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - return true; - } - - template - bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E(& elems)[N]) { - auto* el = elems + circ::index_of(cur); - auto cur_fl = el->f_ct_.load(std::memory_order_acquire); - if (cur_fl != ~static_cast(cur)) { - return false; // empty - } - ++cur; - std::forward(f)(&(el->data_)); - for (unsigned k = 0;;) { - auto cur_rc = el->rc_.load(std::memory_order_acquire); - if ((cur_rc & rc_mask) == 0) { - std::forward(out)(true); - el->f_ct_.store(cur + N - 1, std::memory_order_release); - return true; - } - auto nxt_rc = inc_rc(cur_rc) & ~static_cast(wrapper->connected_id()); - bool last_one = false; - if ((last_one = (nxt_rc & rc_mask) == 0)) { - el->f_ct_.store(cur + N - 1, std::memory_order_release); - } - if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) { - std::forward(out)(last_one); - return true; - } - ipc::yield(k); - } - } -}; - -} // namespace ipc diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/lookupDebugInfo.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/lookupDebugInfo.py deleted file mode 100644 index d4da7de0aed6b87dae6a1d4b417f1c6e099fe1e0..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/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/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/components/carousel.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/components/carousel.py deleted file mode 100644 index 00a064420f1361e7be8e69e3542dcfa7a04a2bc9..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/components/carousel.py +++ /dev/null @@ -1,22 +0,0 @@ -"""gr.Carousel() component.""" - -from gradio_client.serializing import SimpleSerializable - -from gradio.components.base import IOComponent -from gradio.events import Changeable - - -class Carousel(IOComponent, Changeable, SimpleSerializable): - """ - Deprecated Component - """ - - def __init__( - self, - *args, - **kwargs, - ): - raise DeprecationWarning( - "The Carousel component is deprecated. Please consider using the Gallery " - "component, which can be used to display images (and optional captions).", - ) diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/tunneling.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/tunneling.py deleted file mode 100644 index 7249ff57c7a0ef4610fcf0baf9976629267fa784..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/tunneling.py +++ /dev/null @@ -1,103 +0,0 @@ -import atexit -import os -import platform -import re -import stat -import subprocess -from pathlib import Path -from typing import List - -import requests - -VERSION = "0.2" -CURRENT_TUNNELS: List["Tunnel"] = [] - -machine = platform.machine() -if machine == "x86_64": - machine = "amd64" - -BINARY_REMOTE_NAME = f"frpc_{platform.system().lower()}_{machine.lower()}" -EXTENSION = ".exe" if os.name == "nt" else "" -BINARY_URL = f"https://cdn-media.huggingface.co/frpc-gradio-{VERSION}/{BINARY_REMOTE_NAME}{EXTENSION}" - -BINARY_FILENAME = f"{BINARY_REMOTE_NAME}_v{VERSION}" -BINARY_FOLDER = Path(__file__).parent -BINARY_PATH = f"{BINARY_FOLDER / BINARY_FILENAME}" - - -class Tunnel: - def __init__(self, remote_host, remote_port, local_host, local_port, share_token): - self.proc = None - self.url = None - self.remote_host = remote_host - self.remote_port = remote_port - self.local_host = local_host - self.local_port = local_port - self.share_token = share_token - - @staticmethod - def download_binary(): - if not Path(BINARY_PATH).exists(): - resp = requests.get(BINARY_URL) - - if resp.status_code == 403: - raise OSError( - f"Cannot set up a share link as this platform is incompatible. Please " - f"create a GitHub issue with information about your platform: {platform.uname()}" - ) - - resp.raise_for_status() - - # Save file data to local copy - with open(BINARY_PATH, "wb") as file: - file.write(resp.content) - st = os.stat(BINARY_PATH) - os.chmod(BINARY_PATH, st.st_mode | stat.S_IEXEC) - - def start_tunnel(self) -> str: - self.download_binary() - self.url = self._start_tunnel(BINARY_PATH) - return self.url - - def kill(self): - if self.proc is not None: - print(f"Killing tunnel {self.local_host}:{self.local_port} <> {self.url}") - self.proc.terminate() - self.proc = None - - def _start_tunnel(self, binary: str) -> str: - CURRENT_TUNNELS.append(self) - command = [ - binary, - "http", - "-n", - self.share_token, - "-l", - str(self.local_port), - "-i", - self.local_host, - "--uc", - "--sd", - "random", - "--ue", - "--server_addr", - f"{self.remote_host}:{self.remote_port}", - "--disable_log_color", - ] - self.proc = subprocess.Popen( - command, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) - atexit.register(self.kill) - url = "" - while url == "": - if self.proc.stdout is None: - continue - line = self.proc.stdout.readline() - line = line.decode("utf-8") - if "start proxy success" in line: - result = re.search("start proxy success: (.+)\n", line) - if result is None: - raise ValueError("Could not create share URL") - else: - url = result.group(1) - return url diff --git a/spaces/Dao3/chatwithdocs/README.md b/spaces/Dao3/chatwithdocs/README.md deleted file mode 100644 index 9e590154589e00e87b1725565744f5469bee5742..0000000000000000000000000000000000000000 --- a/spaces/Dao3/chatwithdocs/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: FileGPT -emoji: 🐢 -colorFrom: blue -colorTo: green -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: mit -duplicated_from: davila7/filegpt ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/DragGan/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/dnnlib/__init__.py b/spaces/DragGan/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/dnnlib/__init__.py deleted file mode 100644 index c73940d81233142ae3dcd9a37b7ec2185c5d5fc5..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/dnnlib/__init__.py +++ /dev/null @@ -1,9 +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. - -from .util import EasyDict, make_cache_dir_path diff --git a/spaces/DragGan/DragGan-Inversion/stylegan_human/pti/training/coaches/multi_id_coach.py b/spaces/DragGan/DragGan-Inversion/stylegan_human/pti/training/coaches/multi_id_coach.py deleted file mode 100644 index 50210f7086e6613e50c057d1503b97359ad3359f..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan-Inversion/stylegan_human/pti/training/coaches/multi_id_coach.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) SenseTime Research. All rights reserved. - -import os - -import torch -from tqdm import tqdm - -from pti.pti_configs import paths_config, hyperparameters, global_config -from pti.training.coaches.base_coach import BaseCoach -from utils.log_utils import log_images_from_w - - -class MultiIDCoach(BaseCoach): - - def __init__(self, data_loader, use_wandb): - super().__init__(data_loader, use_wandb) - - def train(self): - self.G.synthesis.train() - self.G.mapping.train() - - w_path_dir = f'{paths_config.embedding_base_dir}/{paths_config.input_data_id}' - os.makedirs(w_path_dir, exist_ok=True) - os.makedirs( - f'{w_path_dir}/{paths_config.pti_results_keyword}', exist_ok=True) - - use_ball_holder = True - w_pivots = [] - images = [] - - for fname, image in self.data_loader: - if self.image_counter >= hyperparameters.max_images_to_invert: - break - - image_name = fname[0] - if hyperparameters.first_inv_type == 'w+': - embedding_dir = f'{w_path_dir}/{paths_config.e4e_results_keyword}/{image_name}' - else: - embedding_dir = f'{w_path_dir}/{paths_config.pti_results_keyword}/{image_name}' - os.makedirs(embedding_dir, exist_ok=True) - - w_pivot = self.get_inversion(w_path_dir, image_name, image) - w_pivots.append(w_pivot) - images.append((image_name, image)) - self.image_counter += 1 - - for i in tqdm(range(hyperparameters.max_pti_steps)): - self.image_counter = 0 - - for data, w_pivot in zip(images, w_pivots): - image_name, image = data - - if self.image_counter >= hyperparameters.max_images_to_invert: - break - - real_images_batch = image.to(global_config.device) - - generated_images = self.forward(w_pivot) - loss, l2_loss_val, loss_lpips = self.calc_loss(generated_images, real_images_batch, image_name, - self.G, use_ball_holder, w_pivot) - - self.optimizer.zero_grad() - loss.backward() - self.optimizer.step() - - use_ball_holder = global_config.training_step % hyperparameters.locality_regularization_interval == 0 - - global_config.training_step += 1 - self.image_counter += 1 - - if self.use_wandb: - log_images_from_w(w_pivots, self.G, [image[0] for image in images]) - - # torch.save(self.G, - # f'{paths_config.checkpoints_dir}/model_{global_config.run_name}_multi_id.pt') - snapshot_data = dict() - snapshot_data['G_ema'] = self.G - import pickle - with open(f'{paths_config.checkpoints_dir}/model_{global_config.run_name}_multi_id.pkl', 'wb') as f: - pickle.dump(snapshot_data, f) diff --git a/spaces/EfkTur/nutriscore_app/app.py b/spaces/EfkTur/nutriscore_app/app.py deleted file mode 100644 index cf6e5893f566c90d55d07d19f371cc8c96f44adc..0000000000000000000000000000000000000000 --- a/spaces/EfkTur/nutriscore_app/app.py +++ /dev/null @@ -1,112 +0,0 @@ -import gradio as gr -import pickle -import pandas as pd -from utils import * -import matplotlib.pyplot as plt -import matplotlib.image as mpimg -import sklearn - -with open('./model.pickle', 'rb') as model_file: - pipeline = pickle.load(model_file) - - -def image_score(score): - if score == 'a': - return mpimg.imread('./images/Nutriscore_A.png') - if score == 'b': - return mpimg.imread('./images/Nutriscore_B.png') - if score == 'c': - return mpimg.imread('./images/Nutriscore_C.png') - if score == 'd': - return mpimg.imread('./images/Nutriscore_D.png') - if score == 'e': - return mpimg.imread('./images/Nutriscore_E.png') - - -def greet(energy, saturated_fats, sugars, fibres, proteins, salt): - """ - This is our main predict function - """ - data_file = pd.DataFrame(columns={ - 'energy-kcal_100g', - 'saturated-fat_100g', - 'sugars_100g', - 'fiber_100g', - 'proteins_100g', - 'salt_100g' - }) - - data_file = data_file.append({ - 'energy-kcal_100g':float(energy), - 'saturated-fat_100g':float(saturated_fats), - 'sugars_100g':float(sugars), - 'fiber_100g':float(fibres), - 'proteins_100g':float(proteins), - 'salt_100g':float(salt) - },ignore_index=True) - - nutrigrade = pipeline.predict(data_file) - return image_score(nutrigrade[0]) - -description = ( - "Cette inferface vous donne la possibilité de calculer une estimation "\ - "du nutri-score du produit de votre choix. Pour cela, vous devez vous munir des valeurs\n"\ - "nutritionnelles du produit, qui se trouvent très souvent sur l'arrière du packaging." -) - -article = ( - "

Aide à l'utilisation

"+ - '

  • Veuillez mettre vos nombres avec des "." et non pas des virgules
  • '+ - '
  • Veuillez remplir toutes les cases. Si un champ est manquant sur votre étiquette, veuillez remplir le champ avec la valeur 0
  • '+ - '
  • Si la valeur "sels" n"est pas disponible, veuillez mettre la valeur sodium * 2.5. Cas échéant mettre la valeur 0
  • '+ - "
  • Le score peut mettre jusqu'à 5 secondes pour s'afficher à la première utilisation. Mais en général c'est souvent immédiat.
  • "+ - '
  • Veuillez bien choisir les valeurs pour 100g de produit

'+ - '
'+ - "

Informations supplémentaires

"+ - "

  • Notre algorithme se base sur les quantités d'energie, d'acide gras saturés, de sucres, de fibre, de protéines et de sels pour estimer le nutriscore
  • "+ - "
  • Notre analyse repose sur l'hypothèse que ces 6 facteurs sont les composantes principales du Nutri-score
  • "+ - "
  • Nous avons entrainé nos modèles sur un échantillon de 350,000 produits
  • "+ - "
  • Quelques chiffres sur le nutri-score: Lien

" -) - -energy_kcal_100g = gr.inputs.Number( - label = 'Energy per 100g (in kcal)' -) - -saturated_fats = gr.inputs.Number( - label = 'Saturated fats per 100g (in g)' -) - -sugars = gr.inputs.Number( - label = 'Sugars per 100g (in g)' -) - -fibres = gr.inputs.Number( - label = 'Fibres per 100g (in g)' -) - -proteins = gr.inputs.Number( - label = 'Proteins per 100g (in g)' -) - -salt = gr.inputs.Number( - label = 'Salt per 100g (in g) (Note: Salt = Sodium * 2.5)' -) - -image = gr.outputs.Image( - label = 'Le Nutri-score estimé est:' -) - -iface = gr.Interface( - fn=greet, - inputs=[energy_kcal_100g,saturated_fats,sugars,fibres,proteins,salt], - outputs=image, - article = article, - title = 'Estimation de Nutri-score (Beta)', - description = description, - allow_flagging='never', - theme='default' - ) - - -iface.launch() diff --git a/spaces/Egrt/LicenseGAN/utils/utils_metrics.py b/spaces/Egrt/LicenseGAN/utils/utils_metrics.py deleted file mode 100644 index 0b9bfef0f60a11a9d4c5a47a91f6dee25033ee3c..0000000000000000000000000000000000000000 --- a/spaces/Egrt/LicenseGAN/utils/utils_metrics.py +++ /dev/null @@ -1,69 +0,0 @@ -import torch -import torch.nn.functional as F -from math import exp -import numpy as np - -def gaussian(window_size, sigma): - gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) - return gauss/gauss.sum() - -def create_window(window_size, channel=1): - _1D_window = gaussian(window_size, 1.5).unsqueeze(1) - _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) - window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() - return window - -def SSIM(img1, img2, window_size=11, window=None, size_average=True, full=False): - img1 = (img1 * 0.5 + 0.5) * 255 - img2 = (img2 * 0.5 + 0.5) * 255 - min_val = 0 - max_val = 255 - L = max_val - min_val - img2 = torch.clamp(img2, 0.0, 255.0) - - padd = 0 - (_, channel, height, width) = img1.size() - if window is None: - real_size = min(window_size, height, width) - window = create_window(real_size, channel=channel).to(img1.device) - - mu1 = F.conv2d(img1, window, padding=padd, groups=channel) - mu2 = F.conv2d(img2, window, padding=padd, groups=channel) - - mu1_sq = mu1.pow(2) - mu2_sq = mu2.pow(2) - mu1_mu2 = mu1 * mu2 - - sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq - sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq - sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2 - - C1 = (0.01 * L) ** 2 - C2 = (0.03 * L) ** 2 - - v1 = 2.0 * sigma12 + C2 - v2 = sigma1_sq + sigma2_sq + C2 - cs = torch.mean(v1 / v2) # contrast sensitivity - - ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) - - if size_average: - ret = ssim_map.mean() - else: - ret = ssim_map.mean(1).mean(1).mean(1) - - if full: - return ret, cs - return ret - -def tf_log10(x): - numerator = torch.log(x) - denominator = torch.log(torch.tensor(10.0)) - return numerator / denominator - -def PSNR(img1, img2): - img1 = (img1 * 0.5 + 0.5) * 255 - img2 = (img2 * 0.5 + 0.5) * 255 - max_pixel = 255.0 - img2 = torch.clamp(img2, 0.0, 255.0) - return 10.0 * tf_log10((max_pixel ** 2) / (torch.mean(torch.pow(img2 - img1, 2)))) diff --git a/spaces/EronSamez/RVC_HFmeu/infer/lib/train/utils.py b/spaces/EronSamez/RVC_HFmeu/infer/lib/train/utils.py deleted file mode 100644 index dd965fc4dd2af09e445a7f625f2681460874da7a..0000000000000000000000000000000000000000 --- a/spaces/EronSamez/RVC_HFmeu/infer/lib/train/utils.py +++ /dev/null @@ -1,478 +0,0 @@ -import argparse -import glob -import json -import logging -import os -import subprocess -import sys -import shutil - -import numpy as np -import torch -from scipy.io.wavfile import read - -MATPLOTLIB_FLAG = False - -logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) -logger = logging - - -def load_checkpoint_d(checkpoint_path, combd, sbd, optimizer=None, load_opt=1): - assert os.path.isfile(checkpoint_path) - checkpoint_dict = torch.load(checkpoint_path, map_location="cpu") - - ################## - def go(model, bkey): - saved_state_dict = checkpoint_dict[bkey] - if hasattr(model, "module"): - state_dict = model.module.state_dict() - else: - state_dict = model.state_dict() - new_state_dict = {} - for k, v in state_dict.items(): # 模型需要的shape - try: - new_state_dict[k] = saved_state_dict[k] - if saved_state_dict[k].shape != state_dict[k].shape: - logger.warn( - "shape-%s-mismatch. need: %s, get: %s", - k, - state_dict[k].shape, - saved_state_dict[k].shape, - ) # - raise KeyError - except: - # logger.info(traceback.format_exc()) - logger.info("%s is not in the checkpoint", k) # pretrain缺失的 - new_state_dict[k] = v # 模型自带的随机值 - if hasattr(model, "module"): - model.module.load_state_dict(new_state_dict, strict=False) - else: - model.load_state_dict(new_state_dict, strict=False) - return model - - go(combd, "combd") - model = go(sbd, "sbd") - ############# - logger.info("Loaded model weights") - - iteration = checkpoint_dict["iteration"] - learning_rate = checkpoint_dict["learning_rate"] - if ( - optimizer is not None and load_opt == 1 - ): ###加载不了,如果是空的的话,重新初始化,可能还会影响lr时间表的更新,因此在train文件最外围catch - # try: - optimizer.load_state_dict(checkpoint_dict["optimizer"]) - # except: - # traceback.print_exc() - logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, iteration)) - return model, optimizer, learning_rate, iteration - - -# def load_checkpoint(checkpoint_path, model, optimizer=None): -# assert os.path.isfile(checkpoint_path) -# checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') -# iteration = checkpoint_dict['iteration'] -# learning_rate = checkpoint_dict['learning_rate'] -# if optimizer is not None: -# optimizer.load_state_dict(checkpoint_dict['optimizer']) -# # print(1111) -# saved_state_dict = checkpoint_dict['model'] -# # print(1111) -# -# if hasattr(model, 'module'): -# state_dict = model.module.state_dict() -# else: -# state_dict = model.state_dict() -# new_state_dict= {} -# for k, v in state_dict.items(): -# try: -# new_state_dict[k] = saved_state_dict[k] -# except: -# logger.info("%s is not in the checkpoint" % k) -# new_state_dict[k] = v -# if hasattr(model, 'module'): -# model.module.load_state_dict(new_state_dict) -# else: -# model.load_state_dict(new_state_dict) -# logger.info("Loaded checkpoint '{}' (epoch {})" .format( -# checkpoint_path, iteration)) -# return model, optimizer, learning_rate, iteration -def load_checkpoint(checkpoint_path, model, optimizer=None, load_opt=1): - assert os.path.isfile(checkpoint_path) - checkpoint_dict = torch.load(checkpoint_path, map_location="cpu") - - saved_state_dict = checkpoint_dict["model"] - if hasattr(model, "module"): - state_dict = model.module.state_dict() - else: - state_dict = model.state_dict() - new_state_dict = {} - for k, v in state_dict.items(): # 模型需要的shape - try: - new_state_dict[k] = saved_state_dict[k] - if saved_state_dict[k].shape != state_dict[k].shape: - logger.warn( - "shape-%s-mismatch|need-%s|get-%s", - k, - state_dict[k].shape, - saved_state_dict[k].shape, - ) # - raise KeyError - except: - # logger.info(traceback.format_exc()) - logger.info("%s is not in the checkpoint", k) # pretrain缺失的 - new_state_dict[k] = v # 模型自带的随机值 - if hasattr(model, "module"): - model.module.load_state_dict(new_state_dict, strict=False) - else: - model.load_state_dict(new_state_dict, strict=False) - logger.info("Loaded model weights") - - iteration = checkpoint_dict["iteration"] - learning_rate = checkpoint_dict["learning_rate"] - if ( - optimizer is not None and load_opt == 1 - ): ###加载不了,如果是空的的话,重新初始化,可能还会影响lr时间表的更新,因此在train文件最外围catch - # try: - optimizer.load_state_dict(checkpoint_dict["optimizer"]) - # except: - # traceback.print_exc() - logger.info("Loaded checkpoint '{}' (epoch {})".format(checkpoint_path, iteration)) - return model, optimizer, learning_rate, iteration - - -def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path): - logger.info( - "Saving model and optimizer state at epoch {} to {}".format( - iteration, checkpoint_path - ) - ) - if hasattr(model, "module"): - state_dict = model.module.state_dict() - else: - state_dict = model.state_dict() - torch.save( - { - "model": state_dict, - "iteration": iteration, - "optimizer": optimizer.state_dict(), - "learning_rate": learning_rate, - }, - checkpoint_path, - ) - - -def save_checkpoint_d(combd, sbd, optimizer, learning_rate, iteration, checkpoint_path): - logger.info( - "Saving model and optimizer state at epoch {} to {}".format( - iteration, checkpoint_path - ) - ) - if hasattr(combd, "module"): - state_dict_combd = combd.module.state_dict() - else: - state_dict_combd = combd.state_dict() - if hasattr(sbd, "module"): - state_dict_sbd = sbd.module.state_dict() - else: - state_dict_sbd = sbd.state_dict() - torch.save( - { - "combd": state_dict_combd, - "sbd": state_dict_sbd, - "iteration": iteration, - "optimizer": optimizer.state_dict(), - "learning_rate": learning_rate, - }, - checkpoint_path, - ) - - -def summarize( - writer, - global_step, - scalars={}, - histograms={}, - images={}, - audios={}, - audio_sampling_rate=22050, -): - for k, v in scalars.items(): - writer.add_scalar(k, v, global_step) - for k, v in histograms.items(): - writer.add_histogram(k, v, global_step) - for k, v in images.items(): - writer.add_image(k, v, global_step, dataformats="HWC") - for k, v in audios.items(): - writer.add_audio(k, v, global_step, audio_sampling_rate) - - -def latest_checkpoint_path(dir_path, regex="G_*.pth"): - f_list = glob.glob(os.path.join(dir_path, regex)) - f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f)))) - x = f_list[-1] - logger.debug(x) - return x - - -def plot_spectrogram_to_numpy(spectrogram): - global MATPLOTLIB_FLAG - if not MATPLOTLIB_FLAG: - import matplotlib - - matplotlib.use("Agg") - MATPLOTLIB_FLAG = True - mpl_logger = logging.getLogger("matplotlib") - mpl_logger.setLevel(logging.WARNING) - import matplotlib.pylab as plt - import numpy as np - - fig, ax = plt.subplots(figsize=(10, 2)) - im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none") - plt.colorbar(im, ax=ax) - plt.xlabel("Frames") - plt.ylabel("Channels") - plt.tight_layout() - - fig.canvas.draw() - data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="") - data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) - plt.close() - return data - - -def plot_alignment_to_numpy(alignment, info=None): - global MATPLOTLIB_FLAG - if not MATPLOTLIB_FLAG: - import matplotlib - - matplotlib.use("Agg") - MATPLOTLIB_FLAG = True - mpl_logger = logging.getLogger("matplotlib") - mpl_logger.setLevel(logging.WARNING) - import matplotlib.pylab as plt - import numpy as np - - fig, ax = plt.subplots(figsize=(6, 4)) - im = ax.imshow( - alignment.transpose(), aspect="auto", origin="lower", interpolation="none" - ) - fig.colorbar(im, ax=ax) - xlabel = "Decoder timestep" - if info is not None: - xlabel += "\n\n" + info - plt.xlabel(xlabel) - plt.ylabel("Encoder timestep") - plt.tight_layout() - - fig.canvas.draw() - data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="") - data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) - plt.close() - return data - - -def load_wav_to_torch(full_path): - sampling_rate, data = read(full_path) - return torch.FloatTensor(data.astype(np.float32)), sampling_rate - - -def load_filepaths_and_text(filename, split="|"): - with open(filename, encoding="utf-8") as f: - filepaths_and_text = [line.strip().split(split) for line in f] - return filepaths_and_text - - -def get_hparams(init=True): - """ - todo: - 结尾七人组: - 保存频率、总epoch done - bs done - pretrainG、pretrainD done - 卡号:os.en["CUDA_VISIBLE_DEVICES"] done - if_latest done - 模型:if_f0 done - 采样率:自动选择config done - 是否缓存数据集进GPU:if_cache_data_in_gpu done - - -m: - 自动决定training_files路径,改掉train_nsf_load_pretrain.py里的hps.data.training_files done - -c不要了 - """ - parser = argparse.ArgumentParser() - parser.add_argument( - "-se", - "--save_every_epoch", - type=int, - required=True, - help="checkpoint save frequency (epoch)", - ) - parser.add_argument( - "-te", "--total_epoch", type=int, required=True, help="total_epoch" - ) - parser.add_argument( - "-pg", "--pretrainG", type=str, default="", help="Pretrained Discriminator path" - ) - parser.add_argument( - "-pd", "--pretrainD", type=str, default="", help="Pretrained Generator path" - ) - parser.add_argument("-g", "--gpus", type=str, default="0", help="split by -") - parser.add_argument( - "-bs", "--batch_size", type=int, required=True, help="batch size" - ) - parser.add_argument( - "-e", "--experiment_dir", type=str, required=True, help="experiment dir" - ) # -m - parser.add_argument( - "-sr", "--sample_rate", type=str, required=True, help="sample rate, 32k/40k/48k" - ) - parser.add_argument( - "-sw", - "--save_every_weights", - type=str, - default="0", - help="save the extracted model in weights directory when saving checkpoints", - ) - parser.add_argument( - "-v", "--version", type=str, required=True, help="model version" - ) - parser.add_argument( - "-f0", - "--if_f0", - type=int, - required=True, - help="use f0 as one of the inputs of the model, 1 or 0", - ) - parser.add_argument( - "-l", - "--if_latest", - type=int, - required=True, - help="if only save the latest G/D pth file, 1 or 0", - ) - parser.add_argument( - "-c", - "--if_cache_data_in_gpu", - type=int, - required=True, - help="if caching the dataset in GPU memory, 1 or 0", - ) - - args = parser.parse_args() - name = args.experiment_dir - experiment_dir = os.path.join("./logs", args.experiment_dir) - - config_save_path = os.path.join(experiment_dir, "config.json") - with open(config_save_path, "r") as f: - config = json.load(f) - - hparams = HParams(**config) - hparams.model_dir = hparams.experiment_dir = experiment_dir - hparams.save_every_epoch = args.save_every_epoch - hparams.name = name - hparams.total_epoch = args.total_epoch - hparams.pretrainG = args.pretrainG - hparams.pretrainD = args.pretrainD - hparams.version = args.version - hparams.gpus = args.gpus - hparams.train.batch_size = args.batch_size - hparams.sample_rate = args.sample_rate - hparams.if_f0 = args.if_f0 - hparams.if_latest = args.if_latest - hparams.save_every_weights = args.save_every_weights - hparams.if_cache_data_in_gpu = args.if_cache_data_in_gpu - hparams.data.training_files = "%s/filelist.txt" % experiment_dir - return hparams - - -def get_hparams_from_dir(model_dir): - config_save_path = os.path.join(model_dir, "config.json") - with open(config_save_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams = HParams(**config) - hparams.model_dir = model_dir - return hparams - - -def get_hparams_from_file(config_path): - with open(config_path, "r") as f: - data = f.read() - config = json.loads(data) - - hparams = HParams(**config) - return hparams - - -def check_git_hash(model_dir): - source_dir = os.path.dirname(os.path.realpath(__file__)) - if not os.path.exists(os.path.join(source_dir, ".git")): - logger.warn( - "{} is not a git repository, therefore hash value comparison will be ignored.".format( - source_dir - ) - ) - return - - cur_hash = subprocess.getoutput("git rev-parse HEAD") - - path = os.path.join(model_dir, "githash") - if os.path.exists(path): - saved_hash = open(path).read() - if saved_hash != cur_hash: - logger.warn( - "git hash values are different. {}(saved) != {}(current)".format( - saved_hash[:8], cur_hash[:8] - ) - ) - else: - open(path, "w").write(cur_hash) - - -def get_logger(model_dir, filename="train.log"): - global logger - logger = logging.getLogger(os.path.basename(model_dir)) - logger.setLevel(logging.DEBUG) - - formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s") - if not os.path.exists(model_dir): - os.makedirs(model_dir) - h = logging.FileHandler(os.path.join(model_dir, filename)) - h.setLevel(logging.DEBUG) - h.setFormatter(formatter) - logger.addHandler(h) - return logger - - -class HParams: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - if type(v) == dict: - v = HParams(**v) - self[k] = v - - def keys(self): - return self.__dict__.keys() - - def items(self): - return self.__dict__.items() - - def values(self): - return self.__dict__.values() - - def __len__(self): - return len(self.__dict__) - - def __getitem__(self, key): - return getattr(self, key) - - def __setitem__(self, key, value): - return setattr(self, key, value) - - def __contains__(self, key): - return key in self.__dict__ - - def __repr__(self): - return self.__dict__.__repr__() diff --git a/spaces/EronSamez/RVC_HFmeu/utils/clonerepo_experimental.py b/spaces/EronSamez/RVC_HFmeu/utils/clonerepo_experimental.py deleted file mode 100644 index b0ae02648c1307562cf48033908edcf2996db5e2..0000000000000000000000000000000000000000 --- a/spaces/EronSamez/RVC_HFmeu/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/EuroPython2022/gpt2-TOD_app/README.md b/spaces/EuroPython2022/gpt2-TOD_app/README.md deleted file mode 100644 index fbcee0760ca724b035a107b50669e4ebb9d9d174..0000000000000000000000000000000000000000 --- a/spaces/EuroPython2022/gpt2-TOD_app/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: GPT2 multi-TOD -emoji: 🌎 -colorFrom: pink -colorTo: blue -sdk: gradio -sdk_version: 3.0.24 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Fatima990/text_generator1/README.md b/spaces/Fatima990/text_generator1/README.md deleted file mode 100644 index 49540d7b859816d042f78d5ddbb97806f4d1fd9d..0000000000000000000000000000000000000000 --- a/spaces/Fatima990/text_generator1/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Text Generator1 -emoji: 📈 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.14.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/Felix123456/bingo/src/components/chat-scroll-anchor.tsx b/spaces/Felix123456/bingo/src/components/chat-scroll-anchor.tsx deleted file mode 100644 index ac809f4486a48e134cb69314c3d0dae5e68d614e..0000000000000000000000000000000000000000 --- a/spaces/Felix123456/bingo/src/components/chat-scroll-anchor.tsx +++ /dev/null @@ -1,29 +0,0 @@ -'use client' - -import * as React from 'react' -import { useInView } from 'react-intersection-observer' - -import { useAtBottom } from '@/lib/hooks/use-at-bottom' - -interface ChatScrollAnchorProps { - trackVisibility?: boolean -} - -export function ChatScrollAnchor({ trackVisibility }: ChatScrollAnchorProps) { - const isAtBottom = useAtBottom() - const { ref, entry, inView } = useInView({ - trackVisibility, - delay: 100, - rootMargin: '0px 0px -150px 0px' - }) - - React.useEffect(() => { - if (isAtBottom && trackVisibility && !inView) { - entry?.target.scrollIntoView({ - block: 'start' - }) - } - }, [inView, entry, isAtBottom, trackVisibility]) - - return
-} diff --git a/spaces/Fengbinbin/gpt-academic/crazy_functions/__init__.py b/spaces/Fengbinbin/gpt-academic/crazy_functions/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/FrankZxShen/so-vits-svc-models-ba/modules/F0Predictor/PMF0Predictor.py b/spaces/FrankZxShen/so-vits-svc-models-ba/modules/F0Predictor/PMF0Predictor.py deleted file mode 100644 index ccf4128436c5b7e5a3e720d4597bad0c622d0920..0000000000000000000000000000000000000000 --- a/spaces/FrankZxShen/so-vits-svc-models-ba/modules/F0Predictor/PMF0Predictor.py +++ /dev/null @@ -1,83 +0,0 @@ -from modules.F0Predictor.F0Predictor import F0Predictor -import parselmouth -import numpy as np - -class PMF0Predictor(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 compute_f0(self,wav,p_len=None): - x = wav - if p_len is None: - p_len = x.shape[0]//self.hop_length - else: - assert abs(p_len-x.shape[0]//self.hop_length) < 4, "pad length error" - time_step = self.hop_length / self.sampling_rate * 1000 - f0 = parselmouth.Sound(x, self.sampling_rate).to_pitch_ac( - time_step=time_step / 1000, voicing_threshold=0.6, - pitch_floor=self.f0_min, pitch_ceiling=self.f0_max).selected_array['frequency'] - - pad_size=(p_len - len(f0) + 1) // 2 - if(pad_size>0 or p_len - len(f0) - pad_size>0): - f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant') - f0,uv = self.interpolate_f0(f0) - return f0 - - def compute_f0_uv(self,wav,p_len=None): - x = wav - if p_len is None: - p_len = x.shape[0]//self.hop_length - else: - assert abs(p_len-x.shape[0]//self.hop_length) < 4, "pad length error" - time_step = self.hop_length / self.sampling_rate * 1000 - f0 = parselmouth.Sound(x, self.sampling_rate).to_pitch_ac( - time_step=time_step / 1000, voicing_threshold=0.6, - pitch_floor=self.f0_min, pitch_ceiling=self.f0_max).selected_array['frequency'] - - pad_size=(p_len - len(f0) + 1) // 2 - if(pad_size>0 or p_len - len(f0) - pad_size>0): - f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant') - f0,uv = self.interpolate_f0(f0) - return f0,uv diff --git a/spaces/FridaZuley/RVC_HFKawaii/infer/lib/slicer2.py b/spaces/FridaZuley/RVC_HFKawaii/infer/lib/slicer2.py deleted file mode 100644 index 5b29ee262aa54045e807be2cffeb41687499ba58..0000000000000000000000000000000000000000 --- a/spaces/FridaZuley/RVC_HFKawaii/infer/lib/slicer2.py +++ /dev/null @@ -1,260 +0,0 @@ -import numpy as np - - -# This function is obtained from librosa. -def get_rms( - y, - frame_length=2048, - hop_length=512, - pad_mode="constant", -): - padding = (int(frame_length // 2), int(frame_length // 2)) - y = np.pad(y, padding, mode=pad_mode) - - axis = -1 - # put our new within-frame axis at the end for now - out_strides = y.strides + tuple([y.strides[axis]]) - # Reduce the shape on the framing axis - x_shape_trimmed = list(y.shape) - x_shape_trimmed[axis] -= frame_length - 1 - out_shape = tuple(x_shape_trimmed) + tuple([frame_length]) - xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides) - if axis < 0: - target_axis = axis - 1 - else: - target_axis = axis + 1 - xw = np.moveaxis(xw, -1, target_axis) - # Downsample along the target axis - slices = [slice(None)] * xw.ndim - slices[axis] = slice(0, None, hop_length) - x = xw[tuple(slices)] - - # Calculate power - power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True) - - return np.sqrt(power) - - -class Slicer: - def __init__( - self, - sr: int, - threshold: float = -40.0, - min_length: int = 5000, - min_interval: int = 300, - hop_size: int = 20, - max_sil_kept: int = 5000, - ): - if not min_length >= min_interval >= hop_size: - raise ValueError( - "The following condition must be satisfied: min_length >= min_interval >= hop_size" - ) - if not max_sil_kept >= hop_size: - raise ValueError( - "The following condition must be satisfied: max_sil_kept >= hop_size" - ) - min_interval = sr * min_interval / 1000 - self.threshold = 10 ** (threshold / 20.0) - self.hop_size = round(sr * hop_size / 1000) - self.win_size = min(round(min_interval), 4 * self.hop_size) - self.min_length = round(sr * min_length / 1000 / self.hop_size) - self.min_interval = round(min_interval / self.hop_size) - self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size) - - def _apply_slice(self, waveform, begin, end): - if len(waveform.shape) > 1: - return waveform[ - :, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size) - ] - else: - return waveform[ - begin * self.hop_size : min(waveform.shape[0], end * self.hop_size) - ] - - # @timeit - def slice(self, waveform): - if len(waveform.shape) > 1: - samples = waveform.mean(axis=0) - else: - samples = waveform - if samples.shape[0] <= self.min_length: - return [waveform] - rms_list = get_rms( - y=samples, frame_length=self.win_size, hop_length=self.hop_size - ).squeeze(0) - sil_tags = [] - silence_start = None - clip_start = 0 - for i, rms in enumerate(rms_list): - # Keep looping while frame is silent. - if rms < self.threshold: - # Record start of silent frames. - if silence_start is None: - silence_start = i - continue - # Keep looping while frame is not silent and silence start has not been recorded. - if silence_start is None: - continue - # Clear recorded silence start if interval is not enough or clip is too short - is_leading_silence = silence_start == 0 and i > self.max_sil_kept - need_slice_middle = ( - i - silence_start >= self.min_interval - and i - clip_start >= self.min_length - ) - if not is_leading_silence and not need_slice_middle: - silence_start = None - continue - # Need slicing. Record the range of silent frames to be removed. - if i - silence_start <= self.max_sil_kept: - pos = rms_list[silence_start : i + 1].argmin() + silence_start - if silence_start == 0: - sil_tags.append((0, pos)) - else: - sil_tags.append((pos, pos)) - clip_start = pos - elif i - silence_start <= self.max_sil_kept * 2: - pos = rms_list[ - i - self.max_sil_kept : silence_start + self.max_sil_kept + 1 - ].argmin() - pos += i - self.max_sil_kept - pos_l = ( - rms_list[ - silence_start : silence_start + self.max_sil_kept + 1 - ].argmin() - + silence_start - ) - pos_r = ( - rms_list[i - self.max_sil_kept : i + 1].argmin() - + i - - self.max_sil_kept - ) - if silence_start == 0: - sil_tags.append((0, pos_r)) - clip_start = pos_r - else: - sil_tags.append((min(pos_l, pos), max(pos_r, pos))) - clip_start = max(pos_r, pos) - else: - pos_l = ( - rms_list[ - silence_start : silence_start + self.max_sil_kept + 1 - ].argmin() - + silence_start - ) - pos_r = ( - rms_list[i - self.max_sil_kept : i + 1].argmin() - + i - - self.max_sil_kept - ) - if silence_start == 0: - sil_tags.append((0, pos_r)) - else: - sil_tags.append((pos_l, pos_r)) - clip_start = pos_r - silence_start = None - # Deal with trailing silence. - total_frames = rms_list.shape[0] - if ( - silence_start is not None - and total_frames - silence_start >= self.min_interval - ): - silence_end = min(total_frames, silence_start + self.max_sil_kept) - pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start - sil_tags.append((pos, total_frames + 1)) - # Apply and return slices. - if len(sil_tags) == 0: - return [waveform] - else: - chunks = [] - if sil_tags[0][0] > 0: - chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0])) - for i in range(len(sil_tags) - 1): - chunks.append( - self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]) - ) - if sil_tags[-1][1] < total_frames: - chunks.append( - self._apply_slice(waveform, sil_tags[-1][1], total_frames) - ) - return chunks - - -def main(): - import os.path - from argparse import ArgumentParser - - import librosa - import soundfile - - parser = ArgumentParser() - parser.add_argument("audio", type=str, help="The audio to be sliced") - parser.add_argument( - "--out", type=str, help="Output directory of the sliced audio clips" - ) - parser.add_argument( - "--db_thresh", - type=float, - required=False, - default=-40, - help="The dB threshold for silence detection", - ) - parser.add_argument( - "--min_length", - type=int, - required=False, - default=5000, - help="The minimum milliseconds required for each sliced audio clip", - ) - parser.add_argument( - "--min_interval", - type=int, - required=False, - default=300, - help="The minimum milliseconds for a silence part to be sliced", - ) - parser.add_argument( - "--hop_size", - type=int, - required=False, - default=10, - help="Frame length in milliseconds", - ) - parser.add_argument( - "--max_sil_kept", - type=int, - required=False, - default=500, - help="The maximum silence length kept around the sliced clip, presented in milliseconds", - ) - args = parser.parse_args() - out = args.out - if out is None: - out = os.path.dirname(os.path.abspath(args.audio)) - audio, sr = librosa.load(args.audio, sr=None, mono=False) - slicer = Slicer( - sr=sr, - threshold=args.db_thresh, - min_length=args.min_length, - min_interval=args.min_interval, - hop_size=args.hop_size, - max_sil_kept=args.max_sil_kept, - ) - chunks = slicer.slice(audio) - if not os.path.exists(out): - os.makedirs(out) - for i, chunk in enumerate(chunks): - if len(chunk.shape) > 1: - chunk = chunk.T - soundfile.write( - os.path.join( - out, - f"%s_%d.wav" - % (os.path.basename(args.audio).rsplit(".", maxsplit=1)[0], i), - ), - chunk, - sr, - ) - - -if __name__ == "__main__": - main() diff --git a/spaces/FridaZuley/RVC_HFKawaii/lib/infer_pack/onnx_inference.py b/spaces/FridaZuley/RVC_HFKawaii/lib/infer_pack/onnx_inference.py deleted file mode 100644 index 6517853be49e61c427cf7cd9b5ed203f6d5f367e..0000000000000000000000000000000000000000 --- a/spaces/FridaZuley/RVC_HFKawaii/lib/infer_pack/onnx_inference.py +++ /dev/null @@ -1,145 +0,0 @@ -import onnxruntime -import librosa -import numpy as np -import soundfile - - -class ContentVec: - def __init__(self, vec_path="pretrained/vec-768-layer-12.onnx", device=None): - print("load model(s) from {}".format(vec_path)) - if device == "cpu" or device is None: - providers = ["CPUExecutionProvider"] - elif device == "cuda": - providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] - elif device == "dml": - providers = ["DmlExecutionProvider"] - else: - raise RuntimeError("Unsportted Device") - self.model = onnxruntime.InferenceSession(vec_path, providers=providers) - - def __call__(self, wav): - return self.forward(wav) - - def forward(self, wav): - feats = wav - if feats.ndim == 2: # double channels - feats = feats.mean(-1) - assert feats.ndim == 1, feats.ndim - feats = np.expand_dims(np.expand_dims(feats, 0), 0) - onnx_input = {self.model.get_inputs()[0].name: feats} - logits = self.model.run(None, onnx_input)[0] - return logits.transpose(0, 2, 1) - - -def get_f0_predictor(f0_predictor, hop_length, sampling_rate, **kargs): - if f0_predictor == "pm": - from lib.infer_pack.modules.F0Predictor.PMF0Predictor import PMF0Predictor - - f0_predictor_object = PMF0Predictor( - hop_length=hop_length, sampling_rate=sampling_rate - ) - elif f0_predictor == "harvest": - from lib.infer_pack.modules.F0Predictor.HarvestF0Predictor import ( - HarvestF0Predictor, - ) - - f0_predictor_object = HarvestF0Predictor( - hop_length=hop_length, sampling_rate=sampling_rate - ) - elif f0_predictor == "dio": - from lib.infer_pack.modules.F0Predictor.DioF0Predictor import DioF0Predictor - - f0_predictor_object = DioF0Predictor( - hop_length=hop_length, sampling_rate=sampling_rate - ) - else: - raise Exception("Unknown f0 predictor") - return f0_predictor_object - - -class OnnxRVC: - def __init__( - self, - model_path, - sr=40000, - hop_size=512, - vec_path="vec-768-layer-12", - device="cpu", - ): - vec_path = f"pretrained/{vec_path}.onnx" - self.vec_model = ContentVec(vec_path, device) - if device == "cpu" or device is None: - providers = ["CPUExecutionProvider"] - elif device == "cuda": - providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] - elif device == "dml": - providers = ["DmlExecutionProvider"] - else: - raise RuntimeError("Unsportted Device") - self.model = onnxruntime.InferenceSession(model_path, providers=providers) - self.sampling_rate = sr - self.hop_size = hop_size - - def forward(self, hubert, hubert_length, pitch, pitchf, ds, rnd): - onnx_input = { - self.model.get_inputs()[0].name: hubert, - self.model.get_inputs()[1].name: hubert_length, - self.model.get_inputs()[2].name: pitch, - self.model.get_inputs()[3].name: pitchf, - self.model.get_inputs()[4].name: ds, - self.model.get_inputs()[5].name: rnd, - } - return (self.model.run(None, onnx_input)[0] * 32767).astype(np.int16) - - def inference( - self, - raw_path, - sid, - f0_method="dio", - f0_up_key=0, - pad_time=0.5, - cr_threshold=0.02, - ): - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - f0_predictor = get_f0_predictor( - f0_method, - hop_length=self.hop_size, - sampling_rate=self.sampling_rate, - threshold=cr_threshold, - ) - wav, sr = librosa.load(raw_path, sr=self.sampling_rate) - org_length = len(wav) - if org_length / sr > 50.0: - raise RuntimeError("Reached Max Length") - - wav16k = librosa.resample(wav, orig_sr=self.sampling_rate, target_sr=16000) - wav16k = wav16k - - hubert = self.vec_model(wav16k) - hubert = np.repeat(hubert, 2, axis=2).transpose(0, 2, 1).astype(np.float32) - hubert_length = hubert.shape[1] - - pitchf = f0_predictor.compute_f0(wav, hubert_length) - pitchf = pitchf * 2 ** (f0_up_key / 12) - pitch = pitchf.copy() - f0_mel = 1127 * np.log(1 + pitch / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( - f0_mel_max - f0_mel_min - ) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - pitch = np.rint(f0_mel).astype(np.int64) - - pitchf = pitchf.reshape(1, len(pitchf)).astype(np.float32) - pitch = pitch.reshape(1, len(pitch)) - ds = np.array([sid]).astype(np.int64) - - rnd = np.random.randn(1, 192, hubert_length).astype(np.float32) - hubert_length = np.array([hubert_length]).astype(np.int64) - - out_wav = self.forward(hubert, hubert_length, pitch, pitchf, ds, rnd).squeeze() - out_wav = np.pad(out_wav, (0, 2 * self.hop_size), "constant") - return out_wav[0:org_length] diff --git a/spaces/GXSA/bingo/src/components/turn-counter.tsx b/spaces/GXSA/bingo/src/components/turn-counter.tsx deleted file mode 100644 index 08a9e488f044802a8600f4d195b106567c35aab4..0000000000000000000000000000000000000000 --- a/spaces/GXSA/bingo/src/components/turn-counter.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import React from 'react' -import { Throttling } from '@/lib/bots/bing/types' - -export interface TurnCounterProps { - throttling?: Throttling -} - -export function TurnCounter({ throttling }: TurnCounterProps) { - if (!throttling) { - return null - } - - return ( -
-
- {throttling.numUserMessagesInConversation} - - {throttling.maxNumUserMessagesInConversation} -
-
-
- ) -} diff --git a/spaces/GadaiEngin-GBOX/GadaiEngineNeo-A/gadaiengine_model.py b/spaces/GadaiEngin-GBOX/GadaiEngineNeo-A/gadaiengine_model.py deleted file mode 100644 index 236f2fa4853c7bdf75054f260fa16809de7b7af6..0000000000000000000000000000000000000000 --- a/spaces/GadaiEngin-GBOX/GadaiEngineNeo-A/gadaiengine_model.py +++ /dev/null @@ -1,14 +0,0 @@ -import torch -import torch.nn as nn - -class GadaiEngine_Model(nn.Module): - def __init__(self): - super().__init__() - self.d_li1=nn.Linear(5,57) - self.d_rnn=nn.LSTM(57,57) - self.d_li4=nn.Linear(57,145) - def forward(self,x): - x=self.d_li1(x) - x,_=self.d_rnn(x) - x=self.d_li4(x) - return x \ No newline at end of file diff --git a/spaces/GipAdonimus/Real-Time-Voice-Cloning/utils/__init__.py b/spaces/GipAdonimus/Real-Time-Voice-Cloning/utils/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/GooglyBlox/DalleFork/html2canvas.js b/spaces/GooglyBlox/DalleFork/html2canvas.js deleted file mode 100644 index dd1606d8698aae0ed4877058d6a218fda3a515cd..0000000000000000000000000000000000000000 --- a/spaces/GooglyBlox/DalleFork/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 - - - -
- - -
- - - - -
- - diff --git a/spaces/Hallucinate/demo/AdaBins-main/model_io.py b/spaces/Hallucinate/demo/AdaBins-main/model_io.py deleted file mode 100644 index bca5c177d753ff4c86671b9e34aa30fc212a76fc..0000000000000000000000000000000000000000 --- a/spaces/Hallucinate/demo/AdaBins-main/model_io.py +++ /dev/null @@ -1,72 +0,0 @@ -import os - -import torch - - -def save_weights(model, filename, path="./saved_models"): - if not os.path.isdir(path): - os.makedirs(path) - - fpath = os.path.join(path, filename) - torch.save(model.state_dict(), fpath) - return - - -def save_checkpoint(model, optimizer, epoch, filename, root="./checkpoints"): - if not os.path.isdir(root): - os.makedirs(root) - - fpath = os.path.join(root, filename) - torch.save( - { - "model": model.state_dict(), - "optimizer": optimizer.state_dict(), - "epoch": epoch - } - , fpath) - - -def load_weights(model, filename, path="./saved_models"): - fpath = os.path.join(path, filename) - state_dict = torch.load(fpath) - model.load_state_dict(state_dict) - return model - - -def load_checkpoint(fpath, model, optimizer=None): - ckpt = torch.load(fpath, map_location='cpu') - if optimizer is None: - optimizer = ckpt.get('optimizer', None) - else: - optimizer.load_state_dict(ckpt['optimizer']) - epoch = ckpt['epoch'] - - if 'model' in ckpt: - ckpt = ckpt['model'] - load_dict = {} - for k, v in ckpt.items(): - if k.startswith('module.'): - k_ = k.replace('module.', '') - load_dict[k_] = v - else: - load_dict[k] = v - - modified = {} # backward compatibility to older naming of architecture blocks - for k, v in load_dict.items(): - if k.startswith('adaptive_bins_layer.embedding_conv.'): - k_ = k.replace('adaptive_bins_layer.embedding_conv.', - 'adaptive_bins_layer.conv3x3.') - modified[k_] = v - # del load_dict[k] - - elif k.startswith('adaptive_bins_layer.patch_transformer.embedding_encoder'): - - k_ = k.replace('adaptive_bins_layer.patch_transformer.embedding_encoder', - 'adaptive_bins_layer.patch_transformer.embedding_convPxP') - modified[k_] = v - # del load_dict[k] - else: - modified[k] = v # else keep the original - - model.load_state_dict(modified) - return model, optimizer, epoch diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/legacy_masked_lm.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/legacy_masked_lm.py deleted file mode 100644 index c70608c5a143b7b4fbd8c58dfcf9f873639d379c..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/legacy_masked_lm.py +++ /dev/null @@ -1,177 +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 math - -import torch -import torch.nn.functional as F -from fairseq import metrics, utils -from fairseq.criterions import FairseqCriterion, register_criterion - - -def compute_cross_entropy_loss(logits, targets, ignore_index=-100): - """ - Function to compute the cross entropy loss. The default value of - ignore_index is the same as the default value for F.cross_entropy in - pytorch. - """ - assert logits.size(0) == targets.size( - -1 - ), "Logits and Targets tensor shapes don't match up" - - loss = F.nll_loss( - F.log_softmax(logits, -1, dtype=torch.float32), - targets, - reduction="sum", - ignore_index=ignore_index, - ) - return loss - - -@register_criterion("legacy_masked_lm_loss") -class LegacyMaskedLmLoss(FairseqCriterion): - """ - Implementation for the loss used in masked language model (MLM) training. - This optionally also computes the next sentence prediction (NSP) loss and - adds it to the overall loss based on the specified args. There are three - cases to consider: - 1) Generic MLM training without NSP loss. In this case sentence_targets - and sentence_logits are both None. - 2) BERT training without NSP loss. In this case sentence_targets is - not None but sentence_logits is None and we should not be computing - a sentence level loss. - 3) BERT training with NSP loss. In this case both sentence_targets and - sentence_logits are not None and we should be computing a sentence - level loss. The weight of the sentence level loss is specified as - an argument. - """ - - def __init__(self, task, masked_lm_only, nsp_loss_weight): - super().__init__(task) - self.masked_lm_only = masked_lm_only - self.nsp_loss_weight = nsp_loss_weight - - @staticmethod - def add_args(parser): - """Args for MaskedLM Loss""" - # Default for masked_lm_only is False so as to not break BERT training - parser.add_argument( - "--masked-lm-only", - default=False, - action="store_true", - help="compute MLM loss only", - ) - parser.add_argument( - "--nsp-loss-weight", - default=1.0, - type=float, - help="weight for next sentence prediction" " loss (default 1)", - ) - - def forward(self, model, sample, reduce=True): - """Compute the loss for the given sample. - Returns a tuple with three elements: - 1) the loss - 2) the sample size, which is used as the denominator for the gradient - 3) logging outputs to display while training - """ - lm_logits, output_metadata = model(**sample["net_input"]) - - # reshape lm_logits from (N,T,C) to (N*T,C) - lm_logits = lm_logits.view(-1, lm_logits.size(-1)) - lm_targets = sample["lm_target"].view(-1) - lm_loss = compute_cross_entropy_loss(lm_logits, lm_targets, self.padding_idx) - - # compute the number of tokens for which loss is computed. This is used - # to normalize the loss - ntokens = utils.strip_pad(lm_targets, self.padding_idx).numel() - loss = lm_loss / ntokens - nsentences = sample["nsentences"] - # nsentences = 0 - - # Compute sentence loss if masked_lm_only is False - sentence_loss = None - if not self.masked_lm_only: - sentence_logits = output_metadata["sentence_logits"] - sentence_targets = sample["sentence_target"].view(-1) - # This needs to be recomputed due to some differences between - # TokenBlock and BlockPair dataset. This can be resolved with a - # refactor of BERTModel which we will do in the future. - # TODO: Remove this after refactor of BERTModel - nsentences = sentence_targets.size(0) - - # Check for logits being none which can happen when remove_heads - # is set to true in the BERT model. Ideally we should set - # masked_lm_only to true in this case, but that requires some - # refactor in the BERT model. - if sentence_logits is not None: - sentence_loss = compute_cross_entropy_loss( - sentence_logits, sentence_targets - ) - - loss += self.nsp_loss_weight * (sentence_loss / nsentences) - - # NOTE: as we are summing up per token mlm loss and per sentence nsp loss - # we don't need to use sample_size as denominator for the gradient - # here sample_size is just used for logging - sample_size = 1 - logging_output = { - "loss": utils.item(loss.data) if reduce else loss.data, - "lm_loss": utils.item(lm_loss.data) if reduce else lm_loss.data, - # sentence loss is not always computed - "sentence_loss": ( - (utils.item(sentence_loss.data) if reduce else sentence_loss.data) - if sentence_loss is not None - else 0.0 - ), - "ntokens": ntokens, - "nsentences": nsentences, - "sample_size": sample_size, - } - return loss, sample_size, logging_output - - @staticmethod - def reduce_metrics(logging_outputs) -> None: - """Aggregate logging outputs from data parallel training.""" - lm_loss_sum = sum(log.get("lm_loss", 0) for log in logging_outputs) - sentence_loss_sum = sum(log.get("sentence_loss", 0) for log in logging_outputs) - ntokens = sum(log.get("ntokens", 0) for log in logging_outputs) - nsentences = sum(log.get("nsentences", 0) for log in logging_outputs) - sample_size = sum(log.get("sample_size", 0) for log in logging_outputs) - agg_loss = sum(log.get("loss", 0) for log in logging_outputs) - - metrics.log_scalar( - "loss", - agg_loss / sample_size / math.log(2) if sample_size > 0 else 0.0, - sample_size, - round=3, - ) - metrics.log_scalar( - "lm_loss", - lm_loss_sum / ntokens / math.log(2) if ntokens > 0 else 0.0, - ntokens, - round=3, - ) - metrics.log_scalar( - "sentence_loss", - sentence_loss_sum / nsentences / math.log(2) if nsentences > 0 else 0.0, - nsentences, - round=3, - ) - metrics.log_scalar( - "nll_loss", - lm_loss_sum / ntokens / math.log(2) if ntokens > 0 else 0.0, - ntokens, - round=3, - ) - - @staticmethod - def logging_outputs_can_be_summed() -> bool: - """ - Whether the logging outputs returned by `forward` can be summed - across workers prior to calling `reduce_metrics`. Setting this - to True will improves distributed training speed. - """ - return True diff --git a/spaces/Harveenchadha/Vakyansh-Odia-TTS/ttsv/tts_infer/tts.py b/spaces/Harveenchadha/Vakyansh-Odia-TTS/ttsv/tts_infer/tts.py deleted file mode 100644 index b373de8d62ce4aeb6ba5db5a07e8b018c347217b..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/Vakyansh-Odia-TTS/ttsv/tts_infer/tts.py +++ /dev/null @@ -1,158 +0,0 @@ -from __future__ import absolute_import, division, print_function, unicode_literals -from typing import Tuple -import sys -from argparse import ArgumentParser - -import torch -import numpy as np -import os -import json -import torch - -sys.path.append(os.path.join(os.path.dirname(__file__), "../src/glow_tts")) - -from scipy.io.wavfile import write -from hifi.env import AttrDict -from hifi.models import Generator - - -from text import text_to_sequence -import commons -import models -import utils - - -def check_directory(dir): - if not os.path.exists(dir): - sys.exit("Error: {} directory does not exist".format(dir)) - - -class TextToMel: - def __init__(self, glow_model_dir, device="cuda"): - self.glow_model_dir = glow_model_dir - check_directory(self.glow_model_dir) - self.device = device - self.hps, self.glow_tts_model = self.load_glow_tts() - pass - - def load_glow_tts(self): - hps = utils.get_hparams_from_dir(self.glow_model_dir) - checkpoint_path = utils.latest_checkpoint_path(self.glow_model_dir) - symbols = list(hps.data.punc) + list(hps.data.chars) - glow_tts_model = models.FlowGenerator( - len(symbols) + getattr(hps.data, "add_blank", False), - out_channels=hps.data.n_mel_channels, - **hps.model - ) # .to(self.device) - - if self.device == "cuda": - glow_tts_model.to("cuda") - - utils.load_checkpoint(checkpoint_path, glow_tts_model) - glow_tts_model.decoder.store_inverse() - _ = glow_tts_model.eval() - - return hps, glow_tts_model - - def generate_mel(self, text, noise_scale=0.667, length_scale=1.0): - symbols = list(self.hps.data.punc) + list(self.hps.data.chars) - cleaner = self.hps.data.text_cleaners - if getattr(self.hps.data, "add_blank", False): - text_norm = text_to_sequence(text, symbols, cleaner) - text_norm = commons.intersperse(text_norm, len(symbols)) - else: # If not using "add_blank" option during training, adding spaces at the beginning and the end of utterance improves quality - text = " " + text.strip() + " " - text_norm = text_to_sequence(text, symbols, cleaner) - - sequence = np.array(text_norm)[None, :] - - del symbols - del cleaner - del text - del text_norm - - if self.device == "cuda": - x_tst = torch.autograd.Variable(torch.from_numpy(sequence)).cuda().long() - x_tst_lengths = torch.tensor([x_tst.shape[1]]).cuda() - else: - x_tst = torch.autograd.Variable(torch.from_numpy(sequence)).long() - x_tst_lengths = torch.tensor([x_tst.shape[1]]) - - with torch.no_grad(): - (y_gen_tst, *_), *_, (attn_gen, *_) = self.glow_tts_model( - x_tst, - x_tst_lengths, - gen=True, - noise_scale=noise_scale, - length_scale=length_scale, - ) - del x_tst - del x_tst_lengths - torch.cuda.empty_cache() - return y_gen_tst - #return y_gen_tst.cpu().detach().numpy() - - -class MelToWav: - def __init__(self, hifi_model_dir, device="cuda"): - self.hifi_model_dir = hifi_model_dir - check_directory(self.hifi_model_dir) - self.device = device - self.h, self.hifi_gan_generator = self.load_hifi_gan() - pass - - def load_hifi_gan(self): - checkpoint_path = utils.latest_checkpoint_path(self.hifi_model_dir, regex="g_*") - config_file = os.path.join(self.hifi_model_dir, "config.json") - data = open(config_file).read() - json_config = json.loads(data) - h = AttrDict(json_config) - torch.manual_seed(h.seed) - - generator = Generator(h).to(self.device) - - assert os.path.isfile(checkpoint_path) - print("Loading '{}'".format(checkpoint_path)) - state_dict_g = torch.load(checkpoint_path, map_location=self.device) - print("Complete.") - - generator.load_state_dict(state_dict_g["generator"]) - - generator.eval() - generator.remove_weight_norm() - - return h, generator - - def generate_wav(self, mel): - #mel = torch.FloatTensor(mel).to(self.device) - - y_g_hat = self.hifi_gan_generator(mel.to(self.device)) # passing through vocoder - audio = y_g_hat.squeeze() - audio = audio * 32768.0 - audio = audio.cpu().detach().numpy().astype("int16") - - del y_g_hat - del mel - torch.cuda.empty_cache() - return audio, self.h.sampling_rate - - -if __name__ == "__main__": - - parser = ArgumentParser() - parser.add_argument("-m", "--model", required=True, type=str) - parser.add_argument("-g", "--gan", 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) - args = parser.parse_args() - - text_to_mel = TextToMel(glow_model_dir=args.model, device=args.device) - mel_to_wav = MelToWav(hifi_model_dir=args.gan, device=args.device) - - mel = text_to_mel.generate_mel(args.text) - audio, sr = mel_to_wav.generate_wav(mel) - - write(filename=args.wav, rate=sr, data=audio) - - pass diff --git a/spaces/HighCWu/Style2Paints-4-Gradio/linefiller/trappedball_fill.py b/spaces/HighCWu/Style2Paints-4-Gradio/linefiller/trappedball_fill.py deleted file mode 100644 index c354f2a51e1e18f634bdaefb8dab68640c317943..0000000000000000000000000000000000000000 --- a/spaces/HighCWu/Style2Paints-4-Gradio/linefiller/trappedball_fill.py +++ /dev/null @@ -1,436 +0,0 @@ -import cv2 -import numpy as np -from scipy.ndimage import label -from numba import njit - - -def get_ball_structuring_element(radius): - """Get a ball shape structuring element with specific radius for morphology operation. - The radius of ball usually equals to (leaking_gap_size / 2). - - # Arguments - radius: radius of ball shape. - - # Returns - an array of ball structuring element. - """ - return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1)) - - -def get_unfilled_point(image): - """Get points belong to unfilled(value==255) area. - - # Arguments - image: an image. - - # Returns - an array of points. - """ - y, x = np.where(image == 255) - - return np.stack((x.astype(int), y.astype(int)), axis=-1) - - -def exclude_area(image, radius): - """Perform erosion on image to exclude points near the boundary. - We want to pick part using floodfill from the seed point after dilation. - When the seed point is near boundary, it might not stay in the fill, and would - not be a valid point for next floodfill operation. So we ignore these points with erosion. - - # Arguments - image: an image. - radius: radius of ball shape. - - # Returns - an image after dilation. - """ - return cv2.morphologyEx(image, cv2.MORPH_ERODE, get_ball_structuring_element(radius), anchor=(-1, -1), iterations=1) - - -def trapped_ball_fill_single(image, seed_point, radius): - """Perform a single trapped ball fill operation. - - # Arguments - image: an image. the image should consist of white background, black lines and black fills. - the white area is unfilled area, and the black area is filled area. - seed_point: seed point for trapped-ball fill, a tuple (integer, integer). - radius: radius of ball shape. - # Returns - an image after filling. - """ - ball = get_ball_structuring_element(radius) - - pass1 = np.full(image.shape, 255, np.uint8) - pass2 = np.full(image.shape, 255, np.uint8) - - im_inv = cv2.bitwise_not(image) - - # Floodfill the image - mask1 = cv2.copyMakeBorder(im_inv, 1, 1, 1, 1, cv2.BORDER_CONSTANT, 0) - _, pass1, _, _ = cv2.floodFill(pass1, mask1, seed_point, 0, 0, 0, 4) - - # Perform dilation on image. The fill areas between gaps became disconnected. - pass1 = cv2.morphologyEx(pass1, cv2.MORPH_DILATE, ball, anchor=(-1, -1), iterations=1) - mask2 = cv2.copyMakeBorder(pass1, 1, 1, 1, 1, cv2.BORDER_CONSTANT, 0) - - # Floodfill with seed point again to select one fill area. - _, pass2, _, rect = cv2.floodFill(pass2, mask2, seed_point, 0, 0, 0, 4) - # Perform erosion on the fill result leaking-proof fill. - pass2 = cv2.morphologyEx(pass2, cv2.MORPH_ERODE, ball, anchor=(-1, -1), iterations=1) - - return pass2 - - -def trapped_ball_fill_multi(image, radius, method='mean', max_iter=1000): - """Perform multi trapped ball fill operations until all valid areas are filled. - - # Arguments - image: an image. The image should consist of white background, black lines and black fills. - the white area is unfilled area, and the black area is filled area. - radius: radius of ball shape. - method: method for filtering the fills. - 'max' is usually with large radius for select large area such as background. - max_iter: max iteration number. - # Returns - an array of fills' points. - """ - print('trapped-ball ' + str(radius)) - - unfill_area = image - filled_area, filled_area_size, result = [], [], [] - - for _ in range(max_iter): - points = get_unfilled_point(exclude_area(unfill_area, radius)) - - if not len(points) > 0: - break - - fill = trapped_ball_fill_single(unfill_area, (points[0][0], points[0][1]), radius) - unfill_area = cv2.bitwise_and(unfill_area, fill) - - filled_area.append(np.where(fill == 0)) - filled_area_size.append(len(np.where(fill == 0)[0])) - - filled_area_size = np.asarray(filled_area_size) - - if method == 'max': - area_size_filter = np.max(filled_area_size) - elif method == 'median': - area_size_filter = np.median(filled_area_size) - elif method == 'mean': - area_size_filter = np.mean(filled_area_size) - else: - area_size_filter = 0 - - result_idx = np.where(filled_area_size >= area_size_filter)[0] - - for i in result_idx: - result.append(filled_area[i]) - - return result - - -def flood_fill_single(im, seed_point): - """Perform a single flood fill operation. - - # Arguments - image: an image. the image should consist of white background, black lines and black fills. - the white area is unfilled area, and the black area is filled area. - seed_point: seed point for trapped-ball fill, a tuple (integer, integer). - # Returns - an image after filling. - """ - pass1 = np.full(im.shape, 255, np.uint8) - - im_inv = cv2.bitwise_not(im) - - mask1 = cv2.copyMakeBorder(im_inv, 1, 1, 1, 1, cv2.BORDER_CONSTANT, 0) - _, pass1, _, _ = cv2.floodFill(pass1, mask1, seed_point, 0, 0, 0, 4) - - return pass1 - - -@njit -def count_all(labeled_array, all_counts): - M = labeled_array.shape[0] - N = labeled_array.shape[1] - for x in range(M): - for y in range(N): - i = labeled_array[x, y] - 1 - if i > -1: - all_counts[i] = all_counts[i] + 1 - return - - -@njit -def trace_all(labeled_array, xs, ys, cs): - M = labeled_array.shape[0] - N = labeled_array.shape[1] - for x in range(M): - for y in range(N): - current_label = labeled_array[x, y] - 1 - if current_label > -1: - current_label_count = cs[current_label] - xs[current_label][current_label_count] = x - ys[current_label][current_label_count] = y - cs[current_label] = current_label_count + 1 - return - - -def find_all(labeled_array): - hist_size = int(np.max(labeled_array)) - if hist_size == 0: - return [] - all_counts = [0 for _ in range(hist_size)] - count_all(labeled_array, all_counts) - xs = [np.zeros(shape=(item, ), dtype=np.uint32) for item in all_counts] - ys = [np.zeros(shape=(item, ), dtype=np.uint32) for item in all_counts] - cs = [0 for item in all_counts] - trace_all(labeled_array, xs, ys, cs) - filled_area = [] - for _ in range(hist_size): - filled_area.append((xs[_], ys[_])) - return filled_area - - -def flood_fill_multi(image, merge=False): - print('floodfill') - - labeled_array, num_features = label(image / 255) - print('floodfill_ok1') - - filled_area = find_all(labeled_array) - - print('floodfill_ok2') - - if merge: - new_fill = [] - for item in filled_area: - if len(item[0]) > 8: - new_fill.append(item) - return new_fill - - print('floodfill_ok3') - - return filled_area - - -def old_flood_fill_multi(image, max_iter=20000): - """Perform multi flood fill operations until all valid areas are filled. - This operation will fill all rest areas, which may result large amount of fills. - - # Arguments - image: an image. the image should contain white background, black lines and black fills. - the white area is unfilled area, and the black area is filled area. - max_iter: max iteration number. - # Returns - an array of fills' points. - """ - print('floodfill') - - unfill_area = image - filled_area = [] - - for _ in range(max_iter): - points = get_unfilled_point(unfill_area) - - if not len(points) > 0: - break - - fill = flood_fill_single(unfill_area, (points[0][0], points[0][1])) - unfill_area = cv2.bitwise_and(unfill_area, fill) - - filled_area.append(np.where(fill == 0)) - - return filled_area - - -def mark_fill(image, fills): - """Mark filled areas with 0. - - # Arguments - image: an image. - fills: an array of fills' points. - # Returns - an image. - """ - result = image.copy() - - for fill in fills: - result[fill] = 0 - - return result - - -def build_fill_map(image, fills): - """Make an image(array) with each pixel(element) marked with fills' id. id of line is 0. - - # Arguments - image: an image. - fills: an array of fills' points. - # Returns - an array. - """ - result = np.zeros(image.shape[:2], np.int) - - for index, fill in enumerate(fills): - - if(len(fill[0]) == 0): - continue - - result[fill] = index + 1 - - return result - - -def show_fill_map(fillmap): - """Mark filled areas with colors. It is useful for visualization. - - # Arguments - image: an image. - fills: an array of fills' points. - # Returns - an image. - """ - # Generate color for each fill randomly. - colors = np.random.randint(0, 255, (np.max(fillmap) + 1, 3)) - # Id of line is 0, and its color is black. - colors[0] = [0, 0, 0] - - return colors[fillmap] - - -def get_bounding_rect(points): - """Get a bounding rect of points. - - # Arguments - points: array of points. - # Returns - rect coord - """ - x1, y1, x2, y2 = np.min(points[1]), np.min(points[0]), np.max(points[1]), np.max(points[0]) - return x1, y1, x2, y2 - - -def get_border_bounding_rect(h, w, p1, p2, r): - """Get a valid bounding rect in the image with border of specific size. - - # Arguments - h: image max height. - w: image max width. - p1: start point of rect. - p2: end point of rect. - r: border radius. - # Returns - rect coord - """ - x1, y1, x2, y2 = p1[0], p1[1], p2[0], p2[1] - - x1 = x1 - r if 0 < x1 - r else 0 - y1 = y1 - r if 0 < y1 - r else 0 - x2 = x2 + r + 1 if x2 + r + 1 < w else w - y2 = y2 + r + 1 if y2 + r + 1 < h else h - - return x1, y1, x2, y2 - - -def get_border_point(points, rect, max_height, max_width): - """Get border points of a fill area - - # Arguments - points: points of fill . - rect: bounding rect of fill. - max_height: image max height. - max_width: image max width. - # Returns - points , convex shape of points - """ - # Get a local bounding rect. - border_rect = get_border_bounding_rect(max_height, max_width, rect[:2], rect[2:], 2) - - # Get fill in rect. - fill = np.zeros((border_rect[3] - border_rect[1], border_rect[2] - border_rect[0]), np.uint8) - # Move points to the rect. - fill[(points[0] - border_rect[1], points[1] - border_rect[0])] = 255 - - # Get shape. - _, contours, _ = cv2.findContours(fill, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) - # approx_shape = cv2.approxPolyDP(contours[0], 0.02 * cv2.arcLength(contours[0], True), True) - - # Get border pixel. - # Structuring element in cross shape is used instead of box to get 4-connected border. - cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) - border_pixel_mask = cv2.morphologyEx(fill, cv2.MORPH_DILATE, cross, anchor=(-1, -1), iterations=1) - fill - border_pixel_points = np.where(border_pixel_mask == 255) - - # Transform points back to fillmap. - border_pixel_points = (border_pixel_points[0] + border_rect[1], border_pixel_points[1] + border_rect[0]) - - return border_pixel_points - - -def merge_fill(fillmap, max_iter=20): - """Merge fill areas. - - # Arguments - fillmap: an image. - max_iter: max iteration number. - # Returns - an image. - """ - max_height, max_width = fillmap.shape[:2] - result = fillmap.copy() - - for i in range(max_iter): - print('merge ' + str(i + 1)) - - result[np.where(fillmap == 0)] = 0 - - fill_id = np.unique(result.flatten()) - fills = [] - - for j in fill_id: - point = np.where(result == j) - - fills.append({ - 'id': j, - 'point': point, - 'area': len(point[0]), - }) - - for j, f in enumerate(fills): - # ignore lines - if f['id'] == 0: - continue - - if f['area'] < 5: - result[f['point']] = 0 - - if len(fill_id) == len(np.unique(result.flatten())): - break - - return result - - -def merge_one(fillmap): - result = fillmap.copy() - print('merge') - result[np.where(fillmap == 0)] = 0 - fill_id = np.unique(result.flatten()) - fills = [] - for j in fill_id: - point = np.where(result == j) - fills.append({ - 'id': j, - 'point': point, - 'area': len(point[0]), - }) - for j, f in enumerate(fills): - # ignore lines - if f['id'] == 0: - continue - - if f['area'] < 5: - result[f['point']] = 0 - return result - diff --git a/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.a8b38f58.js b/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.a8b38f58.js deleted file mode 100644 index 673ba74d2ef2d0a215e957b49f16c7c7b46d7f63..0000000000000000000000000000000000000000 --- a/spaces/HighCWu/anime-colorization-with-hint/gradio-modified/gradio/templates/frontend/assets/index.a8b38f58.js +++ /dev/null @@ -1,2 +0,0 @@ -import{S as T,i as H,s as L,e as S,b as c,Y as C,d as f,f as d,x as M,n as g,F as j,I as q,P as B,c as h,m as b,j as v,k,o as w,R as D,T as E,a as F,U as I,V as K,K as P}from"./index.396f4a72.js";function R(n){let e;return{c(){e=S("div"),c(e,"id",n[0]),c(e,"class","output-markdown gr-prose"),C(e,"max-width","100%"),f(e,"min-h-[6rem]",n[3]),f(e,"hidden",!n[1])},m(a,t){d(a,e,t),e.innerHTML=n[2],n[5](e)},p(a,[t]){t&4&&(e.innerHTML=a[2]),t&1&&c(e,"id",a[0]),t&8&&f(e,"min-h-[6rem]",a[3]),t&2&&f(e,"hidden",!a[1])},i:M,o:M,d(a){a&&g(e),n[5](null)}}}function U(n,e,a){let{elem_id:t=""}=e,{visible:l=!0}=e,{value:u}=e,{min_height:o=!1}=e;const m=j();let i;function r(s){q[s?"unshift":"push"](()=>{i=s,a(4,i)})}return n.$$set=s=>{"elem_id"in s&&a(0,t=s.elem_id),"visible"in s&&a(1,l=s.visible),"value"in s&&a(2,u=s.value),"min_height"in s&&a(3,o=s.min_height)},n.$$.update=()=>{n.$$.dirty&4&&m("change")},[t,l,u,o,i,r]}class V extends T{constructor(e){super(),H(this,e,U,R,L,{elem_id:0,visible:1,value:2,min_height:3})}}function Y(n){let e,a,t,l,u;const o=[n[3],{variant:"center"}];let m={};for(let i=0;i{"label"in s&&a(4,t=s.label),"elem_id"in s&&a(0,l=s.elem_id),"visible"in s&&a(1,u=s.visible),"value"in s&&a(2,o=s.value),"loading_status"in s&&a(3,m=s.loading_status)},n.$$.update=()=>{n.$$.dirty&16&&i("change")},[l,u,o,m,t,r]}class A extends T{constructor(e){super(),H(this,e,z,p,L,{label:4,elem_id:0,visible:1,value:2,loading_status:3})}}var J=A;const N=["static"],O=n=>({type:"string",description:"HTML rendering of markdown"});export{J as Component,O as document,N as modes}; -//# sourceMappingURL=index.a8b38f58.js.map diff --git a/spaces/Ikaros521/moe-tts/mel_processing.py b/spaces/Ikaros521/moe-tts/mel_processing.py deleted file mode 100644 index 3e252e76320522a8a4195a60665168f22769aec2..0000000000000000000000000000000000000000 --- a/spaces/Ikaros521/moe-tts/mel_processing.py +++ /dev/null @@ -1,101 +0,0 @@ -import torch -import torch.utils.data -from librosa.filters import mel as librosa_mel_fn - -MAX_WAV_VALUE = 32768.0 - - -def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): - """ - PARAMS - ------ - C: compression factor - """ - return torch.log(torch.clamp(x, min=clip_val) * C) - - -def dynamic_range_decompression_torch(x, C=1): - """ - PARAMS - ------ - C: compression factor used to compress - """ - return torch.exp(x) / C - - -def spectral_normalize_torch(magnitudes): - output = dynamic_range_compression_torch(magnitudes) - return output - - -def spectral_de_normalize_torch(magnitudes): - output = dynamic_range_decompression_torch(magnitudes) - return output - - -mel_basis = {} -hann_window = {} - - -def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False): - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - global hann_window - dtype_device = str(y.dtype) + '_' + str(y.device) - wnsize_dtype_device = str(win_size) + '_' + dtype_device - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], - center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - return spec - - -def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax): - global mel_basis - dtype_device = str(spec.dtype) + '_' + str(spec.device) - fmax_dtype_device = str(fmax) + '_' + dtype_device - if fmax_dtype_device not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device) - spec = torch.matmul(mel_basis[fmax_dtype_device], spec) - spec = spectral_normalize_torch(spec) - return spec - - -def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False): - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - global mel_basis, hann_window - dtype_device = str(y.dtype) + '_' + str(y.device) - fmax_dtype_device = str(fmax) + '_' + dtype_device - wnsize_dtype_device = str(win_size) + '_' + dtype_device - if fmax_dtype_device not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device) - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], - center=center, pad_mode='reflect', normalized=False, onesided=True) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - - spec = torch.matmul(mel_basis[fmax_dtype_device], spec) - spec = spectral_normalize_torch(spec) - - return spec diff --git a/spaces/IntelligenzaArtificiale/code-generation/generation/intro.md b/spaces/IntelligenzaArtificiale/code-generation/generation/intro.md deleted file mode 100644 index 4ac5141bdf14447e65c5944e1eb6fa04eabf92c4..0000000000000000000000000000000000000000 --- a/spaces/IntelligenzaArtificiale/code-generation/generation/intro.md +++ /dev/null @@ -1,4 +0,0 @@ -In this section you can prompt the following models to generate Python code: CodeParrot 1.5B, InCoder 1B and CodeGen 2B. - -* For CodeGen, there are a larger [models](https://huggingface.co/Salesforce/codegen-16B-mono) available on the 🤗 Hub with 6.1 B and 16.1B parameters, but we use the 2B version to have models of comparable size in this demo. For InCoder too, there is a larger [model](https://huggingface.co/spaces/facebook/incoder-6B) with 6B parameters. -* For InCoder, you can also try the original [demo](https://huggingface.co/spaces/facebook/incoder-demo), which has more tasks and examples. \ No newline at end of file diff --git a/spaces/IwanK/heart_failuere/predict.py b/spaces/IwanK/heart_failuere/predict.py deleted file mode 100644 index 12b612d12545a50333dedc54be8ff5f188c7322b..0000000000000000000000000000000000000000 --- a/spaces/IwanK/heart_failuere/predict.py +++ /dev/null @@ -1,83 +0,0 @@ -import streamlit as st -import pandas as pd -import numpy as np -import pickle -import json - -# Load All Files - -with open('best_model.pkl', 'rb') as file_1: - model = pickle.load(file_1) - -with open('model_scaler_std.pkl', 'rb') as file_2: - model_scaler_std = pickle.load(file_2) - -with open('model_scaler_rbst.pkl','rb') as file_3: - model_scaler_rbst = pickle.load(file_3) - -with open('list_numeric_robust.txt', 'r') as file_4: - list_num_robust = json.load(file_4) - -with open('list_numeric_standard.txt', 'r') as file_5: - list_num_std = json.load(file_5) - -with open('list_numeric_categoric.txt', 'r') as file_6: - list_num_cat = json.load(file_6) - -def run(): - with st.form(key='Heart_Failure_Prediction'): - age = st.number_input('Age', min_value=16, max_value=100, value=59, step=1, help='Usia Pasien') - creatinine_phosphokinase = st.number_input('Creatinine Phosphokinase', min_value=0, max_value=10000, value=280, step=10, help='Enzim CPK dalam darah (mcg/L)') - ejection_fraction = st.number_input('Ejection Fraction', min_value=0, max_value=100, value=25, step=1, help='Persentase darah yang meninggalkan jantung (%)') - platelets = st.number_input('Platelets', min_value=0, max_value=1000000, value=350000, step=100, help='Jumlah trombosit dalam darah (kiloplatelet/mL)') - serum_creatinine = st.number_input('Serum Creatinine', min_value=0.0, max_value=20.0, value=1.0, step=0.1, help='Tingkat serum kreatinin dalam darah (mg/dL)') - serum_sodium = st.number_input('Serum Sodium', min_value=0, max_value=200, value=145, step=1, help='Tingkat natrium serum dalam darah (mEq/L)') - time = st.number_input('Time', min_value=0, max_value=500, value=78, step=1, help='Periode tindak lanjut pasien (hari)') - - anaemia = st.selectbox('Anaemia', ('No', 'Yes'), help='Penurunan sel darah merah atau hemoglobin') - diabetes = st.selectbox('Diabetes', ('No', 'Yes'), help='Apakah pasien memiliki diabetes') - high_blood_pressure = st.selectbox('High Blood Pressure', ('No', 'Yes'), help='Apakah pasien memiliki tekanan darah tinggi') - sex = st.selectbox('Sex', ('Female', 'Male'), help='Jenis kelamin pasien') - smoking = st.selectbox('Smoking', ('No', 'Yes'), help='Apakah pasien merokok') - - submitted = st.form_submit_button('Predict') - - # Create New Data - data_inf = { - 'age': age, - 'creatinine_phosphokinase': creatinine_phosphokinase, - 'ejection_fraction': ejection_fraction, - 'platelets': platelets, - 'serum_creatinine': serum_creatinine, - 'serum_sodium': serum_sodium, - 'time': time, - 'anaemia': 1 if anaemia == 'Yes' else 0, - 'diabetes': 1 if diabetes == 'Yes' else 0, - 'high_blood_pressure': 1 if high_blood_pressure == 'Yes' else 0, - 'sex': 1 if sex == 'Male' else 0, - 'smoking': 1 if smoking == 'Yes' else 0 - } - - # Create a DataFrame from the dictionary data_inf - data_inf = pd.DataFrame([data_inf], index=None) - st.dataframe(data_inf) - - if submitted: - # Reorder the columns of data_inf to match the order used during training - data_inf = data_inf[list_num_robust + list_num_std + list_num_cat] - - # Feature Scaling - data_inf_num_rbs_scaled = model_scaler_rbst.transform(data_inf[list_num_robust]) - data_inf_num_std_scaled = model_scaler_std.transform(data_inf[list_num_std]) - - # Combine the scaled features with the categorical features - data_inf_final = np.concatenate([data_inf_num_rbs_scaled, data_inf_num_std_scaled, data_inf[list_num_cat]], axis=1) - - # Predict using the model - y_pred_inf = model.predict(data_inf_final) - - prediction_label = 'Survived' if y_pred_inf == 0 else 'Not Survived' - st.write('Prediction : ', prediction_label) - -if __name__ == '__main__': - run() diff --git a/spaces/Jacks2003/3D_Photo_Inpainting/mesh.py b/spaces/Jacks2003/3D_Photo_Inpainting/mesh.py deleted file mode 100644 index 95cae5be1c26e517fa4d81bd03325a0f0017f9ad..0000000000000000000000000000000000000000 --- a/spaces/Jacks2003/3D_Photo_Inpainting/mesh.py +++ /dev/null @@ -1,2296 +0,0 @@ -import os -import numpy as np -try: - import cynetworkx as netx -except ImportError: - import networkx as netx -import matplotlib.pyplot as plt -from functools import partial -from vispy import scene, io -from vispy.scene import visuals -from vispy.visuals.filters import Alpha -import cv2 -from moviepy.editor import ImageSequenceClip -from skimage.transform import resize -import time -import copy -import torch -import os -from utils import path_planning, open_small_mask, clean_far_edge, refine_depth_around_edge -from utils import refine_color_around_edge, filter_irrelevant_edge_new, require_depth_edge, clean_far_edge_new -from utils import create_placeholder, refresh_node, find_largest_rect -from mesh_tools import get_depth_from_maps, get_map_from_ccs, get_edge_from_nodes, get_depth_from_nodes, get_rgb_from_nodes, crop_maps_by_size, convert2tensor, recursive_add_edge, update_info, filter_edge, relabel_node, depth_inpainting -from mesh_tools import refresh_bord_depth, enlarge_border, fill_dummy_bord, extrapolate, fill_missing_node, incomplete_node, get_valid_size, dilate_valid_size, size_operation -import transforms3d -import random -from functools import reduce - -def create_mesh(depth, image, int_mtx, config): - H, W, C = image.shape - ext_H, ext_W = H + 2 * config['extrapolation_thickness'], W + 2 * config['extrapolation_thickness'] - LDI = netx.Graph(H=ext_H, W=ext_W, noext_H=H, noext_W=W, cam_param=int_mtx) - xy2depth = {} - int_mtx_pix = int_mtx * np.array([[W], [H], [1.]]) - LDI.graph['cam_param_pix'], LDI.graph['cam_param_pix_inv'] = int_mtx_pix, np.linalg.inv(int_mtx_pix) - disp = 1. / (-depth) - LDI.graph['hoffset'], LDI.graph['woffset'] = config['extrapolation_thickness'], config['extrapolation_thickness'] - LDI.graph['bord_up'], LDI.graph['bord_down'] = LDI.graph['hoffset'] + 0, LDI.graph['hoffset'] + H - LDI.graph['bord_left'], LDI.graph['bord_right'] = LDI.graph['woffset'] + 0, LDI.graph['woffset'] + W - for idx in range(H): - for idy in range(W): - x, y = idx + LDI.graph['hoffset'], idy + LDI.graph['woffset'] - LDI.add_node((x, y, -depth[idx, idy]), - color=image[idx, idy], - disp=disp[idx, idy], - synthesis=False, - cc_id=set()) - xy2depth[(x, y)] = [-depth[idx, idy]] - for x, y, d in LDI.nodes: - two_nes = [ne for ne in [(x+1, y), (x, y+1)] if ne[0] < LDI.graph['bord_down'] and ne[1] < LDI.graph['bord_right']] - [LDI.add_edge((ne[0], ne[1], xy2depth[ne][0]), (x, y, d)) for ne in two_nes] - LDI = calculate_fov(LDI) - image = np.pad(image, - pad_width=((config['extrapolation_thickness'], config['extrapolation_thickness']), - (config['extrapolation_thickness'], config['extrapolation_thickness']), - (0, 0)), - mode='constant') - depth = np.pad(depth, - pad_width=((config['extrapolation_thickness'], config['extrapolation_thickness']), - (config['extrapolation_thickness'], config['extrapolation_thickness'])), - mode='constant') - - return LDI, xy2depth, image, depth - - -def tear_edges(mesh, threshold = 0.00025, xy2depth=None): - remove_edge_list = [] - remove_horizon, remove_vertical = np.zeros((2, mesh.graph['H'], mesh.graph['W'])) - mesh_nodes = mesh.nodes - for edge in mesh.edges: - if abs(mesh_nodes[edge[0]]['disp'] - mesh_nodes[edge[1]]['disp']) > threshold: - remove_edge_list.append((edge[0], edge[1])) - - near, far = edge if abs(edge[0][2]) < abs(edge[1][2]) else edge[::-1] - - mesh_nodes[far]['near'] = [] if mesh_nodes[far].get('near') is None else mesh_nodes[far]['near'].append(near) - mesh_nodes[near]['far'] = [] if mesh_nodes[near].get('far') is None else mesh_nodes[near]['far'].append(far) - - if near[0] == far[0]: - remove_horizon[near[0], np.minimum(near[1], far[1])] = 1 - elif near[1] == far[1]: - remove_vertical[np.minimum(near[0], far[0]), near[1]] = 1 - mesh.remove_edges_from(remove_edge_list) - - remove_edge_list = [] - - dang_horizon = np.where(np.roll(remove_horizon, 1, 0) + np.roll(remove_horizon, -1, 0) - remove_horizon == 2) - dang_vertical = np.where(np.roll(remove_vertical, 1, 1) + np.roll(remove_vertical, -1, 1) - remove_vertical == 2) - - horizon_condition = lambda x, y: mesh.graph['bord_up'] + 1 <= x < mesh.graph['bord_down'] - 1 - vertical_condition = lambda x, y: mesh.graph['bord_left'] + 1 <= y < mesh.graph['bord_right'] - 1 - - prjto3d = lambda x, y: (x, y, xy2depth[(x, y)][0]) - - node_existence = lambda x, y: mesh.has_node(prjto3d(x, y)) - - for x, y in zip(dang_horizon[0], dang_horizon[1]): - if horizon_condition(x, y) and node_existence(x, y) and node_existence(x, y+1): - remove_edge_list.append((prjto3d(x, y), prjto3d(x, y+1))) - for x, y in zip(dang_vertical[0], dang_vertical[1]): - if vertical_condition(x, y) and node_existence(x, y) and node_existence(x+1, y): - remove_edge_list.append((prjto3d(x, y), prjto3d(x+1, y))) - mesh.remove_edges_from(remove_edge_list) - - return mesh - -def calculate_fov(mesh): - k = mesh.graph['cam_param'] - mesh.graph['hFov'] = 2 * np.arctan(1. / (2*k[0, 0])) - mesh.graph['vFov'] = 2 * np.arctan(1. / (2*k[1, 1])) - mesh.graph['aspect'] = mesh.graph['noext_H'] / mesh.graph['noext_W'] - - return mesh - -def calculate_fov_FB(mesh): - mesh.graph['aspect'] = mesh.graph['H'] / mesh.graph['W'] - if mesh.graph['H'] > mesh.graph['W']: - mesh.graph['hFov'] = 0.508015513 - half_short = np.tan(mesh.graph['hFov']/2.0) - half_long = half_short * mesh.graph['aspect'] - mesh.graph['vFov'] = 2.0 * np.arctan(half_long) - else: - mesh.graph['vFov'] = 0.508015513 - half_short = np.tan(mesh.graph['vFov']/2.0) - half_long = half_short / mesh.graph['aspect'] - mesh.graph['hFov'] = 2.0 * np.arctan(half_long) - - return mesh - -def reproject_3d_int_detail(sx, sy, z, k_00, k_02, k_11, k_12, w_offset, h_offset): - abs_z = abs(z) - return [abs_z * ((sy+0.5-w_offset) * k_00 + k_02), abs_z * ((sx+0.5-h_offset) * k_11 + k_12), abs_z] - -def reproject_3d_int_detail_FB(sx, sy, z, w_offset, h_offset, mesh): - if mesh.graph.get('tan_hFov') is None: - mesh.graph['tan_hFov'] = np.tan(mesh.graph['hFov'] / 2.) - if mesh.graph.get('tan_vFov') is None: - mesh.graph['tan_vFov'] = np.tan(mesh.graph['vFov'] / 2.) - - ray = np.array([(-1. + 2. * ((sy+0.5-w_offset)/(mesh.graph['W'] - 1))) * mesh.graph['tan_hFov'], - (1. - 2. * (sx+0.5-h_offset)/(mesh.graph['H'] - 1)) * mesh.graph['tan_vFov'], - -1]) - point_3d = ray * np.abs(z) - - return point_3d - - -def reproject_3d_int(sx, sy, z, mesh): - k = mesh.graph['cam_param_pix_inv'].copy() - if k[0, 2] > 0: - k = np.linalg.inv(k) - ray = np.dot(k, np.array([sy-mesh.graph['woffset'], sx-mesh.graph['hoffset'], 1]).reshape(3, 1)) - - point_3d = ray * np.abs(z) - point_3d = point_3d.flatten() - - return point_3d - -def generate_init_node(mesh, config, min_node_in_cc): - mesh_nodes = mesh.nodes - - info_on_pix = {} - - ccs = sorted(netx.connected_components(mesh), key = len, reverse=True) - remove_nodes = [] - - for cc in ccs: - - remove_flag = True if len(cc) < min_node_in_cc else False - if remove_flag is False: - for (nx, ny, nd) in cc: - info_on_pix[(nx, ny)] = [{'depth':nd, - 'color':mesh_nodes[(nx, ny, nd)]['color'], - 'synthesis':False, - 'disp':mesh_nodes[(nx, ny, nd)]['disp']}] - else: - [remove_nodes.append((nx, ny, nd)) for (nx, ny, nd) in cc] - - for node in remove_nodes: - far_nodes = [] if mesh_nodes[node].get('far') is None else mesh_nodes[node]['far'] - for far_node in far_nodes: - if mesh.has_node(far_node) and mesh_nodes[far_node].get('near') is not None and node in mesh_nodes[far_node]['near']: - mesh_nodes[far_node]['near'].remove(node) - near_nodes = [] if mesh_nodes[node].get('near') is None else mesh_nodes[node]['near'] - for near_node in near_nodes: - if mesh.has_node(near_node) and mesh_nodes[near_node].get('far') is not None and node in mesh_nodes[near_node]['far']: - mesh_nodes[near_node]['far'].remove(node) - - [mesh.remove_node(node) for node in remove_nodes] - - return mesh, info_on_pix - -def get_neighbors(mesh, node): - return [*mesh.neighbors(node)] - -def generate_face(mesh, info_on_pix, config): - H, W = mesh.graph['H'], mesh.graph['W'] - str_faces = [] - num_node = len(mesh.nodes) - ply_flag = config.get('save_ply') - def out_fmt(input, cur_id_b, cur_id_self, cur_id_a, ply_flag): - if ply_flag is True: - input.append(' '.join(['3', cur_id_b, cur_id_self, cur_id_a]) + '\n') - else: - input.append([cur_id_b, cur_id_self, cur_id_a]) - mesh_nodes = mesh.nodes - for node in mesh_nodes: - cur_id_self = mesh_nodes[node]['cur_id'] - ne_nodes = get_neighbors(mesh, node) - four_dir_nes = {'up': [], 'left': [], - 'down': [], 'right': []} - for ne_node in ne_nodes: - store_tuple = [ne_node, mesh_nodes[ne_node]['cur_id']] - if ne_node[0] == node[0]: - if ne_node[1] == ne_node[1] - 1: - four_dir_nes['left'].append(store_tuple) - else: - four_dir_nes['right'].append(store_tuple) - else: - if ne_node[0] == ne_node[0] - 1: - four_dir_nes['up'].append(store_tuple) - else: - four_dir_nes['down'].append(store_tuple) - for node_a, cur_id_a in four_dir_nes['up']: - for node_b, cur_id_b in four_dir_nes['right']: - out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag) - for node_a, cur_id_a in four_dir_nes['right']: - for node_b, cur_id_b in four_dir_nes['down']: - out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag) - for node_a, cur_id_a in four_dir_nes['down']: - for node_b, cur_id_b in four_dir_nes['left']: - out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag) - for node_a, cur_id_a in four_dir_nes['left']: - for node_b, cur_id_b in four_dir_nes['up']: - out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag) - - return str_faces - -def reassign_floating_island(mesh, info_on_pix, image, depth): - H, W = mesh.graph['H'], mesh.graph['W'], - mesh_nodes = mesh.nodes - bord_up, bord_down = mesh.graph['bord_up'], mesh.graph['bord_down'] - bord_left, bord_right = mesh.graph['bord_left'], mesh.graph['bord_right'] - W = mesh.graph['W'] - lost_map = np.zeros((H, W)) - - ''' - (5) is_inside(x, y, xmin, xmax, ymin, ymax) : Check if a pixel(x, y) is inside the border. - (6) get_cross_nes(x, y) : Get the four cross neighbors of pixel(x, y). - ''' - key_exist = lambda d, k: k in d - is_inside = lambda x, y, xmin, xmax, ymin, ymax: xmin <= x < xmax and ymin <= y < ymax - get_cross_nes = lambda x, y: [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)] - ''' - (A) Highlight the pixels on isolated floating island. - (B) Number those isolated floating islands with connected component analysis. - (C) For each isolated island: - (1) Find its longest surrounded depth edge. - (2) Propogate depth from that depth edge to the pixels on the isolated island. - (3) Build the connection between the depth edge and that isolated island. - ''' - for x in range(H): - for y in range(W): - if is_inside(x, y, bord_up, bord_down, bord_left, bord_right) and not(key_exist(info_on_pix, (x, y))): - lost_map[x, y] = 1 - _, label_lost_map = cv2.connectedComponents(lost_map.astype(np.uint8), connectivity=4) - mask = np.zeros((H, W)) - mask[bord_up:bord_down, bord_left:bord_right] = 1 - label_lost_map = (label_lost_map * mask).astype(np.int) - - for i in range(1, label_lost_map.max()+1): - lost_xs, lost_ys = np.where(label_lost_map == i) - surr_edge_ids = {} - for lost_x, lost_y in zip(lost_xs, lost_ys): - if (lost_x, lost_y) == (295, 389) or (lost_x, lost_y) == (296, 389): - import pdb; pdb.set_trace() - for ne in get_cross_nes(lost_x, lost_y): - if key_exist(info_on_pix, ne): - for info in info_on_pix[ne]: - ne_node = (ne[0], ne[1], info['depth']) - if key_exist(mesh_nodes[ne_node], 'edge_id'): - edge_id = mesh_nodes[ne_node]['edge_id'] - surr_edge_ids[edge_id] = surr_edge_ids[edge_id] + [ne_node] if \ - key_exist(surr_edge_ids, edge_id) else [ne_node] - if len(surr_edge_ids) == 0: - continue - edge_id, edge_nodes = sorted([*surr_edge_ids.items()], key=lambda x: len(x[1]), reverse=True)[0] - edge_depth_map = np.zeros((H, W)) - for node in edge_nodes: - edge_depth_map[node[0], node[1]] = node[2] - lost_xs, lost_ys = np.where(label_lost_map == i) - while lost_xs.shape[0] > 0: - lost_xs, lost_ys = np.where(label_lost_map == i) - for lost_x, lost_y in zip(lost_xs, lost_ys): - propagated_depth = [] - real_nes = [] - for ne in get_cross_nes(lost_x, lost_y): - if not(is_inside(ne[0], ne[1], bord_up, bord_down, bord_left, bord_right)) or \ - edge_depth_map[ne[0], ne[1]] == 0: - continue - propagated_depth.append(edge_depth_map[ne[0], ne[1]]) - real_nes.append(ne) - if len(real_nes) == 0: - continue - reassign_depth = np.mean(propagated_depth) - label_lost_map[lost_x, lost_y] = 0 - edge_depth_map[lost_x, lost_y] = reassign_depth - depth[lost_x, lost_y] = -reassign_depth - mesh.add_node((lost_x, lost_y, reassign_depth), color=image[lost_x, lost_y], - synthesis=False, - disp=1./reassign_depth, - cc_id=set()) - info_on_pix[(lost_x, lost_y)] = [{'depth':reassign_depth, - 'color':image[lost_x, lost_y], - 'synthesis':False, - 'disp':1./reassign_depth}] - new_connections = [((lost_x, lost_y, reassign_depth), - (ne[0], ne[1], edge_depth_map[ne[0], ne[1]])) for ne in real_nes] - mesh.add_edges_from(new_connections) - - return mesh, info_on_pix, depth - -def remove_node_feat(mesh, *feats): - mesh_nodes = mesh.nodes - for node in mesh_nodes: - for feat in feats: - mesh_nodes[node][feat] = None - - return mesh - -def update_status(mesh, info_on_pix, depth=None): - ''' - (2) clear_node_feat(G, *fts) : Clear all the node feature on graph G. - (6) get_cross_nes(x, y) : Get the four cross neighbors of pixel(x, y). - ''' - key_exist = lambda d, k: d.get(k) is not None - is_inside = lambda x, y, xmin, xmax, ymin, ymax: xmin <= x < xmax and ymin <= y < ymax - get_cross_nes = lambda x, y: [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)] - append_element = lambda d, k, x: d[k] + [x] if key_exist(d, k) else [x] - - def clear_node_feat(G, fts): - le_nodes = G.nodes - for k in le_nodes: - v = le_nodes[k] - for ft in fts: - if ft in v: - v[ft] = None - - clear_node_feat(mesh, ['edge_id', 'far', 'near']) - bord_up, bord_down = mesh.graph['bord_up'], mesh.graph['bord_down'] - bord_left, bord_right = mesh.graph['bord_left'], mesh.graph['bord_right'] - - le_nodes = mesh.nodes - - for node_key in le_nodes: - if mesh.neighbors(node_key).__length_hint__() == 4: - continue - four_nes = [xx for xx in get_cross_nes(node_key[0], node_key[1]) if - is_inside(xx[0], xx[1], bord_up, bord_down, bord_left, bord_right) and - xx in info_on_pix] - [four_nes.remove((ne_node[0], ne_node[1])) for ne_node in mesh.neighbors(node_key)] - for ne in four_nes: - for info in info_on_pix[ne]: - assert mesh.has_node((ne[0], ne[1], info['depth'])), "No node_key" - ind_node = le_nodes[node_key] - if abs(node_key[2]) > abs(info['depth']): - ind_node['near'] = append_element(ind_node, 'near', (ne[0], ne[1], info['depth'])) - else: - ind_node['far'] = append_element(ind_node, 'far', (ne[0], ne[1], info['depth'])) - if depth is not None: - for key, value in info_on_pix.items(): - if depth[key[0], key[1]] != abs(value[0]['depth']): - value[0]['disp'] = 1. / value[0]['depth'] - depth[key[0], key[1]] = abs(value[0]['depth']) - - return mesh, depth, info_on_pix - else: - return mesh - -def group_edges(LDI, config, image, remove_conflict_ordinal, spdb=False): - - ''' - (1) add_new_node(G, node) : add "node" to graph "G" - (2) add_new_edge(G, node_a, node_b) : add edge "node_a--node_b" to graph "G" - (3) exceed_thre(x, y, thre) : Check if difference between "x" and "y" exceed threshold "thre" - (4) key_exist(d, k) : Check if key "k' exists in dictionary "d" - (5) comm_opp_bg(G, x, y) : Check if node "x" and "y" in graph "G" treat the same opposite node as background - (6) comm_opp_fg(G, x, y) : Check if node "x" and "y" in graph "G" treat the same opposite node as foreground - ''' - add_new_node = lambda G, node: None if G.has_node(node) else G.add_node(node) - add_new_edge = lambda G, node_a, node_b: None if G.has_edge(node_a, node_b) else G.add_edge(node_a, node_b) - exceed_thre = lambda x, y, thre: (abs(x) - abs(y)) > thre - key_exist = lambda d, k: d.get(k) is not None - comm_opp_bg = lambda G, x, y: key_exist(G.nodes[x], 'far') and key_exist(G.nodes[y], 'far') and \ - not(set(G.nodes[x]['far']).isdisjoint(set(G.nodes[y]['far']))) - comm_opp_fg = lambda G, x, y: key_exist(G.nodes[x], 'near') and key_exist(G.nodes[y], 'near') and \ - not(set(G.nodes[x]['near']).isdisjoint(set(G.nodes[y]['near']))) - discont_graph = netx.Graph() - ''' - (A) Skip the pixel at image boundary, we don't want to deal with them. - (B) Identify discontinuity by the number of its neighbor(degree). - If the degree < 4(up/right/buttom/left). We will go through following steps: - (1) Add the discontinuity pixel "node" to graph "discont_graph". - (2) Find "node"'s cross neighbor(up/right/buttom/left) "ne_node". - - If the cross neighbor "ne_node" is a discontinuity pixel(degree("ne_node") < 4), - (a) add it to graph "discont_graph" and build the connection between "ne_node" and "node". - (b) label its cross neighbor as invalid pixels "inval_diag_candi" to avoid building - connection between original discontinuity pixel "node" and "inval_diag_candi". - - Otherwise, find "ne_node"'s cross neighbors, called diagonal candidate "diag_candi". - - The "diag_candi" is diagonal to the original discontinuity pixel "node". - - If "diag_candi" exists, go to step(3). - (3) A diagonal candidate "diag_candi" will be : - - added to the "discont_graph" if its degree < 4. - - connected to the original discontinuity pixel "node" if it satisfied either - one of following criterion: - (a) the difference of disparity between "diag_candi" and "node" is smaller than default threshold. - (b) the "diag_candi" and "node" face the same opposite pixel. (See. function "tear_edges") - (c) Both of "diag_candi" and "node" must_connect to each other. (See. function "combine_end_node") - (C) Aggregate each connected part in "discont_graph" into "discont_ccs" (A.K.A. depth edge). - ''' - for node in LDI.nodes: - if not(LDI.graph['bord_up'] + 1 <= node[0] <= LDI.graph['bord_down'] - 2 and \ - LDI.graph['bord_left'] + 1 <= node[1] <= LDI.graph['bord_right'] - 2): - continue - neighbors = [*LDI.neighbors(node)] - if len(neighbors) < 4: - add_new_node(discont_graph, node) - diag_candi_anc, inval_diag_candi, discont_nes = set(), set(), set() - for ne_node in neighbors: - if len([*LDI.neighbors(ne_node)]) < 4: - add_new_node(discont_graph, ne_node) - add_new_edge(discont_graph, ne_node, node) - discont_nes.add(ne_node) - else: - diag_candi_anc.add(ne_node) - inval_diag_candi = set([inval_diagonal for ne_node in discont_nes for inval_diagonal in LDI.neighbors(ne_node) if \ - abs(inval_diagonal[0] - node[0]) < 2 and abs(inval_diagonal[1] - node[1]) < 2]) - for ne_node in diag_candi_anc: - if ne_node[0] == node[0]: - diagonal_xys = [[ne_node[0] + 1, ne_node[1]], [ne_node[0] - 1, ne_node[1]]] - elif ne_node[1] == node[1]: - diagonal_xys = [[ne_node[0], ne_node[1] + 1], [ne_node[0], ne_node[1] - 1]] - for diag_candi in LDI.neighbors(ne_node): - if [diag_candi[0], diag_candi[1]] in diagonal_xys and LDI.degree(diag_candi) < 4: - if diag_candi not in inval_diag_candi: - if not exceed_thre(1./node[2], 1./diag_candi[2], config['depth_threshold']) or \ - (comm_opp_bg(LDI, diag_candi, node) and comm_opp_fg(LDI, diag_candi, node)): - add_new_node(discont_graph, diag_candi) - add_new_edge(discont_graph, diag_candi, node) - if key_exist(LDI.nodes[diag_candi], 'must_connect') and node in LDI.nodes[diag_candi]['must_connect'] and \ - key_exist(LDI.nodes[node], 'must_connect') and diag_candi in LDI.nodes[node]['must_connect']: - add_new_node(discont_graph, diag_candi) - add_new_edge(discont_graph, diag_candi, node) - if spdb == True: - import pdb; pdb.set_trace() - discont_ccs = [*netx.connected_components(discont_graph)] - ''' - In some corner case, a depth edge "discont_cc" will contain both - foreground(FG) and background(BG) pixels. This violate the assumption that - a depth edge can only composite by one type of pixel(FG or BG). - We need to further divide this depth edge into several sub-part so that the - assumption is satisfied. - (A) A depth edge is invalid if both of its "far_flag"(BG) and - "near_flag"(FG) are True. - (B) If the depth edge is invalid, we need to do: - (1) Find the role("oridinal") of each pixel on the depth edge. - "-1" --> Its opposite pixels has smaller depth(near) than it. - It is a backgorund pixel. - "+1" --> Its opposite pixels has larger depth(far) than it. - It is a foregorund pixel. - "0" --> Some of opposite pixels has larger depth(far) than it, - and some has smaller pixel than it. - It is an ambiguous pixel. - (2) For each pixel "discont_node", check if its neigbhors' roles are consistent. - - If not, break the connection between the neighbor "ne_node" that has a role - different from "discont_node". - - If yes, remove all the role that are inconsistent to its neighbors "ne_node". - (3) Connected component analysis to re-identified those divided depth edge. - (C) Aggregate each connected part in "discont_graph" into "discont_ccs" (A.K.A. depth edge). - ''' - if remove_conflict_ordinal: - new_discont_ccs = [] - num_new_cc = 0 - for edge_id, discont_cc in enumerate(discont_ccs): - near_flag = False - far_flag = False - for discont_node in discont_cc: - near_flag = True if key_exist(LDI.nodes[discont_node], 'far') else near_flag - far_flag = True if key_exist(LDI.nodes[discont_node], 'near') else far_flag - if far_flag and near_flag: - break - if far_flag and near_flag: - for discont_node in discont_cc: - discont_graph.nodes[discont_node]['ordinal'] = \ - np.array([key_exist(LDI.nodes[discont_node], 'far'), - key_exist(LDI.nodes[discont_node], 'near')]) * \ - np.array([-1, 1]) - discont_graph.nodes[discont_node]['ordinal'] = \ - np.sum(discont_graph.nodes[discont_node]['ordinal']) - remove_nodes, remove_edges = [], [] - for discont_node in discont_cc: - ordinal_relation = np.sum([discont_graph.nodes[xx]['ordinal'] \ - for xx in discont_graph.neighbors(discont_node)]) - near_side = discont_graph.nodes[discont_node]['ordinal'] <= 0 - if abs(ordinal_relation) < len([*discont_graph.neighbors(discont_node)]): - remove_nodes.append(discont_node) - for ne_node in discont_graph.neighbors(discont_node): - remove_flag = (near_side and not(key_exist(LDI.nodes[ne_node], 'far'))) or \ - (not near_side and not(key_exist(LDI.nodes[ne_node], 'near'))) - remove_edges += [(discont_node, ne_node)] if remove_flag else [] - else: - if near_side and key_exist(LDI.nodes[discont_node], 'near'): - LDI.nodes[discont_node].pop('near') - elif not(near_side) and key_exist(LDI.nodes[discont_node], 'far'): - LDI.nodes[discont_node].pop('far') - discont_graph.remove_edges_from(remove_edges) - sub_mesh = discont_graph.subgraph(list(discont_cc)).copy() - sub_discont_ccs = [*netx.connected_components(sub_mesh)] - is_redun_near = lambda xx: len(xx) == 1 and xx[0] in remove_nodes and key_exist(LDI.nodes[xx[0]], 'far') - for sub_discont_cc in sub_discont_ccs: - if is_redun_near(list(sub_discont_cc)): - LDI.nodes[list(sub_discont_cc)[0]].pop('far') - new_discont_ccs.append(sub_discont_cc) - else: - new_discont_ccs.append(discont_cc) - discont_ccs = new_discont_ccs - new_discont_ccs = None - if spdb == True: - import pdb; pdb.set_trace() - - for edge_id, edge_cc in enumerate(discont_ccs): - for node in edge_cc: - LDI.nodes[node]['edge_id'] = edge_id - - return discont_ccs, LDI, discont_graph - -def combine_end_node(mesh, edge_mesh, edge_ccs, depth): - import collections - mesh_nodes = mesh.nodes - connect_dict = dict() - for valid_edge_id, valid_edge_cc in enumerate(edge_ccs): - connect_info = [] - for valid_edge_node in valid_edge_cc: - single_connect = set() - for ne_node in mesh.neighbors(valid_edge_node): - if mesh_nodes[ne_node].get('far') is not None: - for fn in mesh_nodes[ne_node].get('far'): - if mesh.has_node(fn) and mesh_nodes[fn].get('edge_id') is not None: - single_connect.add(mesh_nodes[fn]['edge_id']) - if mesh_nodes[ne_node].get('near') is not None: - for fn in mesh_nodes[ne_node].get('near'): - if mesh.has_node(fn) and mesh_nodes[fn].get('edge_id') is not None: - single_connect.add(mesh_nodes[fn]['edge_id']) - connect_info.extend([*single_connect]) - connect_dict[valid_edge_id] = collections.Counter(connect_info) - - end_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - edge_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1 - for valid_edge_id, valid_edge_cc in enumerate(edge_ccs): - for valid_edge_node in valid_edge_cc: - edge_maps[valid_edge_node[0], valid_edge_node[1]] = valid_edge_id - if len([*edge_mesh.neighbors(valid_edge_node)]) == 1: - num_ne = 1 - if num_ne == 1: - end_maps[valid_edge_node[0], valid_edge_node[1]] = valid_edge_node[2] - nxs, nys = np.where(end_maps != 0) - invalid_nodes = set() - for nx, ny in zip(nxs, nys): - if mesh.has_node((nx, ny, end_maps[nx, ny])) is False: - invalid_nodes.add((nx, ny)) - continue - four_nes = [xx for xx in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] \ - if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \ - end_maps[xx[0], xx[1]] != 0] - mesh_nes = [*mesh.neighbors((nx, ny, end_maps[nx, ny]))] - remove_num = 0 - for fne in four_nes: - if (fne[0], fne[1], end_maps[fne[0], fne[1]]) in mesh_nes: - remove_num += 1 - if remove_num == len(four_nes): - invalid_nodes.add((nx, ny)) - for invalid_node in invalid_nodes: - end_maps[invalid_node[0], invalid_node[1]] = 0 - - nxs, nys = np.where(end_maps != 0) - invalid_nodes = set() - for nx, ny in zip(nxs, nys): - if mesh_nodes[(nx, ny, end_maps[nx, ny])].get('edge_id') is None: - continue - else: - self_id = mesh_nodes[(nx, ny, end_maps[nx, ny])].get('edge_id') - self_connect = connect_dict[self_id] if connect_dict.get(self_id) is not None else dict() - four_nes = [xx for xx in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] \ - if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \ - end_maps[xx[0], xx[1]] != 0] - for fne in four_nes: - if mesh_nodes[(fne[0], fne[1], end_maps[fne[0], fne[1]])].get('edge_id') is None: - continue - else: - ne_id = mesh_nodes[(fne[0], fne[1], end_maps[fne[0], fne[1]])]['edge_id'] - if self_connect.get(ne_id) is None or self_connect.get(ne_id) == 1: - continue - else: - invalid_nodes.add((nx, ny)) - for invalid_node in invalid_nodes: - end_maps[invalid_node[0], invalid_node[1]] = 0 - nxs, nys = np.where(end_maps != 0) - invalid_nodes = set() - for nx, ny in zip(nxs, nys): - four_nes = [xx for xx in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] \ - if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \ - end_maps[xx[0], xx[1]] != 0] - for fne in four_nes: - if mesh.has_node((fne[0], fne[1], end_maps[fne[0], fne[1]])): - node_a, node_b = (fne[0], fne[1], end_maps[fne[0], fne[1]]), (nx, ny, end_maps[nx, ny]) - mesh.add_edge(node_a, node_b) - mesh_nodes[node_b]['must_connect'] = set() if mesh_nodes[node_b].get('must_connect') is None else mesh_nodes[node_b]['must_connect'] - mesh_nodes[node_b]['must_connect'].add(node_a) - mesh_nodes[node_b]['must_connect'] |= set([xx for xx in [*edge_mesh.neighbors(node_a)] if \ - (xx[0] - node_b[0]) < 2 and (xx[1] - node_b[1]) < 2]) - mesh_nodes[node_a]['must_connect'] = set() if mesh_nodes[node_a].get('must_connect') is None else mesh_nodes[node_a]['must_connect'] - mesh_nodes[node_a]['must_connect'].add(node_b) - mesh_nodes[node_a]['must_connect'] |= set([xx for xx in [*edge_mesh.neighbors(node_b)] if \ - (xx[0] - node_a[0]) < 2 and (xx[1] - node_a[1]) < 2]) - invalid_nodes.add((nx, ny)) - for invalid_node in invalid_nodes: - end_maps[invalid_node[0], invalid_node[1]] = 0 - - return mesh - -def remove_redundant_edge(mesh, edge_mesh, edge_ccs, info_on_pix, config, redundant_number=1000, invalid=False, spdb=False): - point_to_amount = {} - point_to_id = {} - end_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1 - for valid_edge_id, valid_edge_cc in enumerate(edge_ccs): - for valid_edge_node in valid_edge_cc: - point_to_amount[valid_edge_node] = len(valid_edge_cc) - point_to_id[valid_edge_node] = valid_edge_id - if edge_mesh.has_node(valid_edge_node) is True: - if len([*edge_mesh.neighbors(valid_edge_node)]) == 1: - end_maps[valid_edge_node[0], valid_edge_node[1]] = valid_edge_id - nxs, nys = np.where(end_maps > -1) - point_to_adjoint = {} - for nx, ny in zip(nxs, nys): - adjoint_edges = set([end_maps[x, y] for x, y in [(nx + 1, ny), (nx - 1, ny), (nx, ny + 1), (nx, ny - 1)] if end_maps[x, y] != -1]) - point_to_adjoint[end_maps[nx, ny]] = (point_to_adjoint[end_maps[nx, ny]] | adjoint_edges) if point_to_adjoint.get(end_maps[nx, ny]) is not None else adjoint_edges - valid_edge_ccs = filter_edge(mesh, edge_ccs, config, invalid=invalid) - edge_canvas = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1 - for valid_edge_id, valid_edge_cc in enumerate(valid_edge_ccs): - for valid_edge_node in valid_edge_cc: - edge_canvas[valid_edge_node[0], valid_edge_node[1]] = valid_edge_id - if spdb is True: - plt.imshow(edge_canvas); plt.show() - import pdb; pdb.set_trace() - for valid_edge_id, valid_edge_cc in enumerate(valid_edge_ccs): - end_number = 0 - four_end_number = 0 - eight_end_number = 0 - db_eight_end_number = 0 - if len(valid_edge_cc) > redundant_number: - continue - for valid_edge_node in valid_edge_cc: - if len([*edge_mesh.neighbors(valid_edge_node)]) == 3: - break - elif len([*edge_mesh.neighbors(valid_edge_node)]) == 1: - hx, hy, hz = valid_edge_node - if invalid is False: - eight_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), - (hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id] - if len(eight_nes) == 0: - end_number += 1 - if invalid is True: - four_nes = []; eight_nes = []; db_eight_nes = [] - four_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id] - eight_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), \ - (hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id] - db_eight_nes = [(x, y) for x in range(hx - 2, hx + 3) for y in range(hy - 2, hy + 3) \ - if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id and (x, y) != (hx, hy)] - if len(four_nes) == 0 or len(eight_nes) == 0: - end_number += 1 - if len(four_nes) == 0: - four_end_number += 1 - if len(eight_nes) == 0: - eight_end_number += 1 - if len(db_eight_nes) == 0: - db_eight_end_number += 1 - elif len([*edge_mesh.neighbors(valid_edge_node)]) == 0: - hx, hy, hz = valid_edge_node - four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and \ - mesh.has_edge(valid_edge_node, (x, y, info_on_pix[(x, y)][0]['depth'])) is False] - for ne in four_nes: - try: - if invalid is True or (point_to_amount.get(ne) is None or point_to_amount[ne] < redundant_number) or \ - point_to_id[ne] in point_to_adjoint.get(point_to_id[valid_edge_node], set()): - mesh.add_edge(valid_edge_node, ne) - except: - import pdb; pdb.set_trace() - if (invalid is not True and end_number >= 1) or (invalid is True and end_number >= 2 and eight_end_number >= 1 and db_eight_end_number >= 1): - for valid_edge_node in valid_edge_cc: - hx, hy, _ = valid_edge_node - four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and \ - mesh.has_edge(valid_edge_node, (x, y, info_on_pix[(x, y)][0]['depth'])) is False and \ - (edge_canvas[x, y] == -1 or edge_canvas[x, y] == valid_edge_id)] - for ne in four_nes: - if invalid is True or (point_to_amount.get(ne) is None or point_to_amount[ne] < redundant_number) or \ - point_to_id[ne] in point_to_adjoint.get(point_to_id[valid_edge_node], set()): - mesh.add_edge(valid_edge_node, ne) - - return mesh - -def judge_dangle(mark, mesh, node): - if not (1 <= node[0] < mesh.graph['H']-1) or not(1 <= node[1] < mesh.graph['W']-1): - return mark - mesh_neighbors = [*mesh.neighbors(node)] - mesh_neighbors = [xx for xx in mesh_neighbors if 0 < xx[0] < mesh.graph['H'] - 1 and 0 < xx[1] < mesh.graph['W'] - 1] - if len(mesh_neighbors) >= 3: - return mark - elif len(mesh_neighbors) <= 1: - mark[node[0], node[1]] = (len(mesh_neighbors) + 1) - else: - dan_ne_node_a = mesh_neighbors[0] - dan_ne_node_b = mesh_neighbors[1] - if abs(dan_ne_node_a[0] - dan_ne_node_b[0]) > 1 or \ - abs(dan_ne_node_a[1] - dan_ne_node_b[1]) > 1: - mark[node[0], node[1]] = 3 - - return mark - -def remove_dangling(mesh, edge_ccs, edge_mesh, info_on_pix, image, depth, config): - - tmp_edge_ccs = copy.deepcopy(edge_ccs) - for edge_cc_id, valid_edge_cc in enumerate(tmp_edge_ccs): - if len(valid_edge_cc) > 1 or len(valid_edge_cc) == 0: - continue - single_edge_node = [*valid_edge_cc][0] - hx, hy, hz = single_edge_node - eight_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), - (hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \ - if info_on_pix.get((x, y)) is not None]) - four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \ - if info_on_pix.get((x, y)) is not None] - sub_mesh = mesh.subgraph(eight_nes).copy() - ccs = netx.connected_components(sub_mesh) - four_ccs = [] - for cc_id, _cc in enumerate(ccs): - four_ccs.append(set()) - for cc_node in _cc: - if abs(cc_node[0] - hx) + abs(cc_node[1] - hy) < 2: - four_ccs[cc_id].add(cc_node) - largest_cc = sorted(four_ccs, key=lambda x: (len(x), -np.sum([abs(xx[2] - hz) for xx in x])))[-1] - if len(largest_cc) < 2: - for ne in four_nes: - mesh.add_edge(single_edge_node, ne) - else: - mesh.remove_edges_from([(single_edge_node, ne) for ne in mesh.neighbors(single_edge_node)]) - new_depth = np.mean([xx[2] for xx in largest_cc]) - info_on_pix[(hx, hy)][0]['depth'] = new_depth - info_on_pix[(hx, hy)][0]['disp'] = 1./new_depth - new_node = (hx, hy, new_depth) - mesh = refresh_node(single_edge_node, mesh.node[single_edge_node], new_node, dict(), mesh) - edge_ccs[edge_cc_id] = set([new_node]) - for ne in largest_cc: - mesh.add_edge(new_node, ne) - - mark = np.zeros((mesh.graph['H'], mesh.graph['W'])) - for edge_idx, edge_cc in enumerate(edge_ccs): - for edge_node in edge_cc: - if not (mesh.graph['bord_up'] <= edge_node[0] < mesh.graph['bord_down']-1) or \ - not (mesh.graph['bord_left'] <= edge_node[1] < mesh.graph['bord_right']-1): - continue - mesh_neighbors = [*mesh.neighbors(edge_node)] - mesh_neighbors = [xx for xx in mesh_neighbors \ - if mesh.graph['bord_up'] < xx[0] < mesh.graph['bord_down'] - 1 and \ - mesh.graph['bord_left'] < xx[1] < mesh.graph['bord_right'] - 1] - if len([*mesh.neighbors(edge_node)]) >= 3: - continue - elif len([*mesh.neighbors(edge_node)]) <= 1: - mark[edge_node[0], edge_node[1]] += (len([*mesh.neighbors(edge_node)]) + 1) - else: - dan_ne_node_a = [*mesh.neighbors(edge_node)][0] - dan_ne_node_b = [*mesh.neighbors(edge_node)][1] - if abs(dan_ne_node_a[0] - dan_ne_node_b[0]) > 1 or \ - abs(dan_ne_node_a[1] - dan_ne_node_b[1]) > 1: - mark[edge_node[0], edge_node[1]] += 3 - mxs, mys = np.where(mark == 1) - conn_0_nodes = [(x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']) for x in zip(mxs, mys) \ - if mesh.has_node((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']))] - mxs, mys = np.where(mark == 2) - conn_1_nodes = [(x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']) for x in zip(mxs, mys) \ - if mesh.has_node((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']))] - for node in conn_0_nodes: - hx, hy = node[0], node[1] - four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \ - if info_on_pix.get((x, y)) is not None] - re_depth = {'value' : 0, 'count': 0} - for ne in four_nes: - mesh.add_edge(node, ne) - re_depth['value'] += cc_node[2] - re_depth['count'] += 1. - re_depth = re_depth['value'] / re_depth['count'] - mapping_dict = {node: (node[0], node[1], re_depth)} - info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh) - depth[node[0], node[1]] = abs(re_depth) - mark[node[0], node[1]] = 0 - for node in conn_1_nodes: - hx, hy = node[0], node[1] - eight_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), - (hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \ - if info_on_pix.get((x, y)) is not None]) - self_nes = set([ne2 for ne1 in mesh.neighbors(node) for ne2 in mesh.neighbors(ne1) if ne2 in eight_nes]) - eight_nes = [*(eight_nes - self_nes)] - sub_mesh = mesh.subgraph(eight_nes).copy() - ccs = netx.connected_components(sub_mesh) - largest_cc = sorted(ccs, key=lambda x: (len(x), -np.sum([abs(xx[0] - node[0]) + abs(xx[1] - node[1]) for xx in x])))[-1] - - mesh.remove_edges_from([(xx, node) for xx in mesh.neighbors(node)]) - re_depth = {'value' : 0, 'count': 0} - for cc_node in largest_cc: - if cc_node[0] == node[0] and cc_node[1] == node[1]: - continue - re_depth['value'] += cc_node[2] - re_depth['count'] += 1. - if abs(cc_node[0] - node[0]) + abs(cc_node[1] - node[1]) < 2: - mesh.add_edge(cc_node, node) - try: - re_depth = re_depth['value'] / re_depth['count'] - except: - re_depth = node[2] - renode = (node[0], node[1], re_depth) - mapping_dict = {node: renode} - info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh) - depth[node[0], node[1]] = abs(re_depth) - mark[node[0], node[1]] = 0 - edge_mesh, mesh, mark, info_on_pix = recursive_add_edge(edge_mesh, mesh, info_on_pix, renode, mark) - mxs, mys = np.where(mark == 3) - conn_2_nodes = [(x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']) for x in zip(mxs, mys) \ - if mesh.has_node((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth'])) and \ - mesh.degree((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth'])) == 2] - sub_mesh = mesh.subgraph(conn_2_nodes).copy() - ccs = netx.connected_components(sub_mesh) - for cc in ccs: - candidate_nodes = [xx for xx in cc if sub_mesh.degree(xx) == 1] - for node in candidate_nodes: - if mesh.has_node(node) is False: - continue - ne_node = [xx for xx in mesh.neighbors(node) if xx not in cc][0] - hx, hy = node[0], node[1] - eight_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), - (hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and (x, y, info_on_pix[(x, y)][0]['depth']) not in cc]) - ne_sub_mesh = mesh.subgraph(eight_nes).copy() - ne_ccs = netx.connected_components(ne_sub_mesh) - try: - ne_cc = [ne_cc for ne_cc in ne_ccs if ne_node in ne_cc][0] - except: - import pdb; pdb.set_trace() - largest_cc = [xx for xx in ne_cc if abs(xx[0] - node[0]) + abs(xx[1] - node[1]) == 1] - mesh.remove_edges_from([(xx, node) for xx in mesh.neighbors(node)]) - re_depth = {'value' : 0, 'count': 0} - for cc_node in largest_cc: - re_depth['value'] += cc_node[2] - re_depth['count'] += 1. - mesh.add_edge(cc_node, node) - try: - re_depth = re_depth['value'] / re_depth['count'] - except: - re_depth = node[2] - renode = (node[0], node[1], re_depth) - mapping_dict = {node: renode} - info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh) - depth[node[0], node[1]] = abs(re_depth) - mark[node[0], node[1]] = 0 - edge_mesh, mesh, mark, info_on_pix = recursive_add_edge(edge_mesh, mesh, info_on_pix, renode, mark) - break - if len(cc) == 1: - node = [node for node in cc][0] - hx, hy = node[0], node[1] - nine_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx, hy), (hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), - (hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \ - if info_on_pix.get((x, y)) is not None and mesh.has_node((x, y, info_on_pix[(x, y)][0]['depth']))]) - ne_sub_mesh = mesh.subgraph(nine_nes).copy() - ne_ccs = netx.connected_components(ne_sub_mesh) - for ne_cc in ne_ccs: - if node in ne_cc: - re_depth = {'value' : 0, 'count': 0} - for ne in ne_cc: - if abs(ne[0] - node[0]) + abs(ne[1] - node[1]) == 1: - mesh.add_edge(node, ne) - re_depth['value'] += ne[2] - re_depth['count'] += 1. - re_depth = re_depth['value'] / re_depth['count'] - mapping_dict = {node: (node[0], node[1], re_depth)} - info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh) - depth[node[0], node[1]] = abs(re_depth) - mark[node[0], node[1]] = 0 - - - return mesh, info_on_pix, edge_mesh, depth, mark - -def context_and_holes(mesh, edge_ccs, config, specific_edge_id, specific_edge_loc, depth_feat_model, - connect_points_ccs=None, inpaint_iter=0, filter_edge=False, vis_edge_id=None): - edge_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1 - mask_info = {} - for edge_id, edge_cc in enumerate(edge_ccs): - for edge_node in edge_cc: - edge_maps[edge_node[0], edge_node[1]] = edge_id - - context_ccs = [set() for x in range(len(edge_ccs))] - extend_context_ccs = [set() for x in range(len(edge_ccs))] - extend_erode_context_ccs = [set() for x in range(len(edge_ccs))] - extend_edge_ccs = [set() for x in range(len(edge_ccs))] - accomp_extend_context_ccs = [set() for x in range(len(edge_ccs))] - erode_context_ccs = [set() for x in range(len(edge_ccs))] - broken_mask_ccs = [set() for x in range(len(edge_ccs))] - invalid_extend_edge_ccs = [set() for x in range(len(edge_ccs))] - intouched_ccs = [set() for x in range(len(edge_ccs))] - redundant_ccs = [set() for x in range(len(edge_ccs))] - if inpaint_iter == 0: - background_thickness = config['background_thickness'] - context_thickness = config['context_thickness'] - else: - background_thickness = config['background_thickness_2'] - context_thickness = config['context_thickness_2'] - - mesh_nodes = mesh.nodes - for edge_id, edge_cc in enumerate(edge_ccs): - if context_thickness == 0 or (len(specific_edge_id) > 0 and edge_id not in specific_edge_id): - continue - edge_group = {} - for edge_node in edge_cc: - far_nodes = mesh_nodes[edge_node].get('far') - if far_nodes is None: - continue - for far_node in far_nodes: - if far_node in edge_cc: - continue - context_ccs[edge_id].add(far_node) - if mesh_nodes[far_node].get('edge_id') is not None: - if edge_group.get(mesh_nodes[far_node]['edge_id']) is None: - edge_group[mesh_nodes[far_node]['edge_id']] = set() - edge_group[mesh_nodes[far_node]['edge_id']].add(far_node) - if len(edge_cc) > 2: - for edge_key in [*edge_group.keys()]: - if len(edge_group[edge_key]) == 1: - context_ccs[edge_id].remove([*edge_group[edge_key]][0]) - for edge_id, edge_cc in enumerate(edge_ccs): - if inpaint_iter != 0: - continue - tmp_intouched_nodes = set() - for edge_node in edge_cc: - raw_intouched_nodes = set(mesh_nodes[edge_node].get('near')) if mesh_nodes[edge_node].get('near') is not None else set() - tmp_intouched_nodes |= set([xx for xx in raw_intouched_nodes if mesh_nodes[xx].get('edge_id') is not None and \ - len(context_ccs[mesh_nodes[xx].get('edge_id')]) > 0]) - intouched_ccs[edge_id] |= tmp_intouched_nodes - tmp_intouched_nodes = None - mask_ccs = copy.deepcopy(edge_ccs) - forbidden_len = 3 - forbidden_map = np.ones((mesh.graph['H'] - forbidden_len, mesh.graph['W'] - forbidden_len)) - forbidden_map = np.pad(forbidden_map, ((forbidden_len, forbidden_len), (forbidden_len, forbidden_len)), mode='constant').astype(np.bool) - cur_tmp_mask_map = np.zeros_like(forbidden_map).astype(np.bool) - passive_background = 10 if 10 is not None else background_thickness - passive_context = 1 if 1 is not None else context_thickness - - for edge_id, edge_cc in enumerate(edge_ccs): - cur_mask_cc = None; cur_mask_cc = [] - cur_context_cc = None; cur_context_cc = [] - cur_accomp_near_cc = None; cur_accomp_near_cc = [] - cur_invalid_extend_edge_cc = None; cur_invalid_extend_edge_cc = [] - cur_comp_far_cc = None; cur_comp_far_cc = [] - tmp_erode = [] - if len(context_ccs[edge_id]) == 0 or (len(specific_edge_id) > 0 and edge_id not in specific_edge_id): - continue - for i in range(max(background_thickness, context_thickness)): - cur_tmp_mask_map.fill(False) - if i == 0: - tmp_mask_nodes = copy.deepcopy(mask_ccs[edge_id]) - tmp_intersect_nodes = [] - tmp_intersect_context_nodes = [] - mask_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool) - context_depth = np.zeros((mesh.graph['H'], mesh.graph['W'])) - comp_cnt_depth = np.zeros((mesh.graph['H'], mesh.graph['W'])) - connect_map = np.zeros((mesh.graph['H'], mesh.graph['W'])) - for node in tmp_mask_nodes: - mask_map[node[0], node[1]] = True - depth_count = 0 - if mesh_nodes[node].get('far') is not None: - for comp_cnt_node in mesh_nodes[node]['far']: - comp_cnt_depth[node[0], node[1]] += abs(comp_cnt_node[2]) - depth_count += 1 - if depth_count > 0: - comp_cnt_depth[node[0], node[1]] = comp_cnt_depth[node[0], node[1]] / depth_count - connect_node = [] - if mesh_nodes[node].get('connect_point_id') is not None: - connect_node.append(mesh_nodes[node]['connect_point_id']) - connect_point_id = np.bincount(connect_node).argmax() if len(connect_node) > 0 else -1 - if connect_point_id > -1 and connect_points_ccs is not None: - for xx in connect_points_ccs[connect_point_id]: - if connect_map[xx[0], xx[1]] == 0: - connect_map[xx[0], xx[1]] = xx[2] - if mesh_nodes[node].get('connect_point_exception') is not None: - for xx in mesh_nodes[node]['connect_point_exception']: - if connect_map[xx[0], xx[1]] == 0: - connect_map[xx[0], xx[1]] = xx[2] - tmp_context_nodes = [*context_ccs[edge_id]] - tmp_erode.append([*context_ccs[edge_id]]) - context_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool) - if (context_map.astype(np.uint8) * mask_map.astype(np.uint8)).max() > 0: - import pdb; pdb.set_trace() - for node in tmp_context_nodes: - context_map[node[0], node[1]] = True - context_depth[node[0], node[1]] = node[2] - context_map[mask_map == True] = False - if (context_map.astype(np.uint8) * mask_map.astype(np.uint8)).max() > 0: - import pdb; pdb.set_trace() - tmp_intouched_nodes = [*intouched_ccs[edge_id]] - intouched_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool) - for node in tmp_intouched_nodes: intouched_map[node[0], node[1]] = True - intouched_map[mask_map == True] = False - tmp_redundant_nodes = set() - tmp_noncont_nodes = set() - noncont_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool) - intersect_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool) - intersect_context_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool) - if i > passive_background and inpaint_iter == 0: - new_tmp_intersect_nodes = None - new_tmp_intersect_nodes = [] - for node in tmp_intersect_nodes: - nes = mesh.neighbors(node) - for ne in nes: - if bool(context_map[ne[0], ne[1]]) is False and \ - bool(mask_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True and \ - bool(intouched_map[ne[0], ne[1]]) is False and\ - bool(intersect_map[ne[0], ne[1]]) is False and\ - bool(intersect_context_map[ne[0], ne[1]]) is False: - break_flag = False - if (i - passive_background) % 2 == 0 and (i - passive_background) % 8 != 0: - four_nes = [xx for xx in[[ne[0] - 1, ne[1]], [ne[0] + 1, ne[1]], [ne[0], ne[1] - 1], [ne[0], ne[1] + 1]] \ - if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W']] - for fne in four_nes: - if bool(mask_map[fne[0], fne[1]]) is True: - break_flag = True - break - if break_flag is True: - continue - intersect_map[ne[0], ne[1]] = True - new_tmp_intersect_nodes.append(ne) - tmp_intersect_nodes = None - tmp_intersect_nodes = new_tmp_intersect_nodes - - if i > passive_context and inpaint_iter == 1: - new_tmp_intersect_context_nodes = None - new_tmp_intersect_context_nodes = [] - for node in tmp_intersect_context_nodes: - nes = mesh.neighbors(node) - for ne in nes: - if bool(context_map[ne[0], ne[1]]) is False and \ - bool(mask_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True and \ - bool(intouched_map[ne[0], ne[1]]) is False and\ - bool(intersect_map[ne[0], ne[1]]) is False and \ - bool(intersect_context_map[ne[0], ne[1]]) is False: - intersect_context_map[ne[0], ne[1]] = True - new_tmp_intersect_context_nodes.append(ne) - tmp_intersect_context_nodes = None - tmp_intersect_context_nodes = new_tmp_intersect_context_nodes - - new_tmp_mask_nodes = None - new_tmp_mask_nodes = [] - for node in tmp_mask_nodes: - four_nes = {xx:[] for xx in [(node[0] - 1, node[1]), (node[0] + 1, node[1]), (node[0], node[1] - 1), (node[0], node[1] + 1)] if \ - 0 <= xx[0] < connect_map.shape[0] and 0 <= xx[1] < connect_map.shape[1]} - if inpaint_iter > 0: - for ne in four_nes.keys(): - if connect_map[ne[0], ne[1]] == True: - tmp_context_nodes.append((ne[0], ne[1], connect_map[ne[0], ne[1]])) - context_map[ne[0], ne[1]] = True - nes = mesh.neighbors(node) - if inpaint_iter > 0: - for ne in nes: four_nes[(ne[0], ne[1])].append(ne[2]) - nes = [] - for kfne, vfnes in four_nes.items(): vfnes.sort(key = lambda xx: abs(xx), reverse=True) - for kfne, vfnes in four_nes.items(): - for vfne in vfnes: nes.append((kfne[0], kfne[1], vfne)) - for ne in nes: - if bool(context_map[ne[0], ne[1]]) is False and \ - bool(mask_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True and \ - bool(intouched_map[ne[0], ne[1]]) is False and \ - bool(intersect_map[ne[0], ne[1]]) is False and \ - bool(intersect_context_map[ne[0], ne[1]]) is False: - if i == passive_background and inpaint_iter == 0: - if np.any(context_map[max(ne[0] - 1, 0):min(ne[0] + 2, mesh.graph['H']), max(ne[1] - 1, 0):min(ne[1] + 2, mesh.graph['W'])]) == True: - intersect_map[ne[0], ne[1]] = True - tmp_intersect_nodes.append(ne) - continue - if i < background_thickness: - if inpaint_iter == 0: - cur_mask_cc.append(ne) - elif mesh_nodes[ne].get('inpaint_id') == 1: - cur_mask_cc.append(ne) - else: - continue - mask_ccs[edge_id].add(ne) - if inpaint_iter == 0: - if comp_cnt_depth[node[0], node[1]] > 0 and comp_cnt_depth[ne[0], ne[1]] == 0: - comp_cnt_depth[ne[0], ne[1]] = comp_cnt_depth[node[0], node[1]] - if mesh_nodes[ne].get('far') is not None: - for comp_far_node in mesh_nodes[ne]['far']: - cur_comp_far_cc.append(comp_far_node) - cur_accomp_near_cc.append(ne) - cur_invalid_extend_edge_cc.append(comp_far_node) - if mesh_nodes[ne].get('edge_id') is not None and \ - len(context_ccs[mesh_nodes[ne].get('edge_id')]) > 0: - intouched_fars = set(mesh_nodes[ne].get('far')) if mesh_nodes[ne].get('far') is not None else set() - accum_intouched_fars = set(intouched_fars) - for intouched_far in intouched_fars: - accum_intouched_fars |= set([*mesh.neighbors(intouched_far)]) - for intouched_far in accum_intouched_fars: - if bool(mask_map[intouched_far[0], intouched_far[1]]) is True or \ - bool(context_map[intouched_far[0], intouched_far[1]]) is True: - continue - tmp_redundant_nodes.add(intouched_far) - intouched_map[intouched_far[0], intouched_far[1]] = True - if mesh_nodes[ne].get('near') is not None: - intouched_nears = set(mesh_nodes[ne].get('near')) - for intouched_near in intouched_nears: - if bool(mask_map[intouched_near[0], intouched_near[1]]) is True or \ - bool(context_map[intouched_near[0], intouched_near[1]]) is True: - continue - tmp_redundant_nodes.add(intouched_near) - intouched_map[intouched_near[0], intouched_near[1]] = True - if not (mesh_nodes[ne].get('inpaint_id') != 1 and inpaint_iter == 1): - new_tmp_mask_nodes.append(ne) - mask_map[ne[0], ne[1]] = True - tmp_mask_nodes = new_tmp_mask_nodes - - new_tmp_context_nodes = None - new_tmp_context_nodes = [] - for node in tmp_context_nodes: - nes = mesh.neighbors(node) - if inpaint_iter > 0: - four_nes = {(node[0] - 1, node[1]):[], (node[0] + 1, node[1]):[], (node[0], node[1] - 1):[], (node[0], node[1] + 1):[]} - for ne in nes: four_nes[(ne[0], ne[1])].append(ne[2]) - nes = [] - for kfne, vfnes in four_nes.items(): vfnes.sort(key = lambda xx: abs(xx), reverse=True) - for kfne, vfnes in four_nes.items(): - for vfne in vfnes: nes.append((kfne[0], kfne[1], vfne)) - for ne in nes: - mask_flag = (bool(mask_map[ne[0], ne[1]]) is False) - if bool(context_map[ne[0], ne[1]]) is False and mask_flag and \ - bool(forbidden_map[ne[0], ne[1]]) is True and bool(noncont_map[ne[0], ne[1]]) is False and \ - bool(intersect_context_map[ne[0], ne[1]]) is False: - if i == passive_context and inpaint_iter == 1: - mnes = mesh.neighbors(ne) - if any([mask_map[mne[0], mne[1]] == True for mne in mnes]) is True: - intersect_context_map[ne[0], ne[1]] = True - tmp_intersect_context_nodes.append(ne) - continue - if False and mesh_nodes[ne].get('near') is not None and mesh_nodes[ne].get('edge_id') != edge_id: - noncont_nears = set(mesh_nodes[ne].get('near')) - for noncont_near in noncont_nears: - if bool(context_map[noncont_near[0], noncont_near[1]]) is False: - tmp_noncont_nodes.add(noncont_near) - noncont_map[noncont_near[0], noncont_near[1]] = True - new_tmp_context_nodes.append(ne) - context_map[ne[0], ne[1]] = True - context_depth[ne[0], ne[1]] = ne[2] - cur_context_cc.extend(new_tmp_context_nodes) - tmp_erode.append(new_tmp_context_nodes) - tmp_context_nodes = None - tmp_context_nodes = new_tmp_context_nodes - new_tmp_intouched_nodes = None; new_tmp_intouched_nodes = [] - - for node in tmp_intouched_nodes: - if bool(context_map[node[0], node[1]]) is True or bool(mask_map[node[0], node[1]]) is True: - continue - nes = mesh.neighbors(node) - - for ne in nes: - if bool(context_map[ne[0], ne[1]]) is False and \ - bool(mask_map[ne[0], ne[1]]) is False and \ - bool(intouched_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True: - new_tmp_intouched_nodes.append(ne) - intouched_map[ne[0], ne[1]] = True - tmp_intouched_nodes = None - tmp_intouched_nodes = set(new_tmp_intouched_nodes) - new_tmp_redundant_nodes = None; new_tmp_redundant_nodes = [] - for node in tmp_redundant_nodes: - if bool(context_map[node[0], node[1]]) is True or \ - bool(mask_map[node[0], node[1]]) is True: - continue - nes = mesh.neighbors(node) - - for ne in nes: - if bool(context_map[ne[0], ne[1]]) is False and \ - bool(mask_map[ne[0], ne[1]]) is False and \ - bool(intouched_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True: - new_tmp_redundant_nodes.append(ne) - intouched_map[ne[0], ne[1]] = True - tmp_redundant_nodes = None - tmp_redundant_nodes = set(new_tmp_redundant_nodes) - new_tmp_noncont_nodes = None; new_tmp_noncont_nodes = [] - for node in tmp_noncont_nodes: - if bool(context_map[node[0], node[1]]) is True or \ - bool(mask_map[node[0], node[1]]) is True: - continue - nes = mesh.neighbors(node) - rmv_flag = False - for ne in nes: - if bool(context_map[ne[0], ne[1]]) is False and \ - bool(mask_map[ne[0], ne[1]]) is False and \ - bool(noncont_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True: - patch_context_map = context_map[max(ne[0] - 1, 0):min(ne[0] + 2, context_map.shape[0]), - max(ne[1] - 1, 0):min(ne[1] + 2, context_map.shape[1])] - if bool(np.any(patch_context_map)) is True: - new_tmp_noncont_nodes.append(ne) - noncont_map[ne[0], ne[1]] = True - tmp_noncont_nodes = None - tmp_noncont_nodes = set(new_tmp_noncont_nodes) - if inpaint_iter == 0: - depth_dict = get_depth_from_maps(context_map, mask_map, context_depth, mesh.graph['H'], mesh.graph['W'], log_depth=config['log_depth']) - mask_size = get_valid_size(depth_dict['mask']) - mask_size = dilate_valid_size(mask_size, depth_dict['mask'], dilate=[20, 20]) - context_size = get_valid_size(depth_dict['context']) - context_size = dilate_valid_size(context_size, depth_dict['context'], dilate=[20, 20]) - union_size = size_operation(mask_size, context_size, operation='+') - depth_dict = depth_inpainting(None, None, None, None, mesh, config, union_size, depth_feat_model, None, given_depth_dict=depth_dict, spdb=False) - near_depth_map, raw_near_depth_map = np.zeros((mesh.graph['H'], mesh.graph['W'])), np.zeros((mesh.graph['H'], mesh.graph['W'])) - filtered_comp_far_cc, filtered_accomp_near_cc = set(), set() - for node in cur_accomp_near_cc: - near_depth_map[node[0], node[1]] = depth_dict['output'][node[0], node[1]] - raw_near_depth_map[node[0], node[1]] = node[2] - for node in cur_comp_far_cc: - four_nes = [xx for xx in [(node[0] - 1, node[1]), (node[0] + 1, node[1]), (node[0], node[1] - 1), (node[0], node[1] + 1)] \ - if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \ - near_depth_map[xx[0], xx[1]] != 0 and \ - abs(near_depth_map[xx[0], xx[1]]) < abs(node[2])] - if len(four_nes) > 0: - filtered_comp_far_cc.add(node) - for ne in four_nes: - filtered_accomp_near_cc.add((ne[0], ne[1], -abs(raw_near_depth_map[ne[0], ne[1]]))) - cur_comp_far_cc, cur_accomp_near_cc = filtered_comp_far_cc, filtered_accomp_near_cc - mask_ccs[edge_id] |= set(cur_mask_cc) - context_ccs[edge_id] |= set(cur_context_cc) - accomp_extend_context_ccs[edge_id] |= set(cur_accomp_near_cc).intersection(cur_mask_cc) - extend_edge_ccs[edge_id] |= set(cur_accomp_near_cc).intersection(cur_mask_cc) - extend_context_ccs[edge_id] |= set(cur_comp_far_cc) - invalid_extend_edge_ccs[edge_id] |= set(cur_invalid_extend_edge_cc) - erode_size = [0] - for tmp in tmp_erode: - erode_size.append(len(tmp)) - if len(erode_size) > 1: - erode_size[-1] += erode_size[-2] - if inpaint_iter == 0: - tmp_width = config['depth_edge_dilate'] - else: - tmp_width = 0 - while float(erode_size[tmp_width]) / (erode_size[-1] + 1e-6) > 0.3: - tmp_width = tmp_width - 1 - try: - if tmp_width == 0: - erode_context_ccs[edge_id] = set([]) - else: - erode_context_ccs[edge_id] = set(reduce(lambda x, y : x + y, [] + tmp_erode[:tmp_width])) - except: - import pdb; pdb.set_trace() - erode_context_cc = copy.deepcopy(erode_context_ccs[edge_id]) - for erode_context_node in erode_context_cc: - if (inpaint_iter != 0 and (mesh_nodes[erode_context_node].get('inpaint_id') is None or - mesh_nodes[erode_context_node].get('inpaint_id') == 0)): - erode_context_ccs[edge_id].remove(erode_context_node) - else: - context_ccs[edge_id].remove(erode_context_node) - context_map = np.zeros((mesh.graph['H'], mesh.graph['W'])) - for context_node in context_ccs[edge_id]: - context_map[context_node[0], context_node[1]] = 1 - extend_context_ccs[edge_id] = extend_context_ccs[edge_id] - mask_ccs[edge_id] - accomp_extend_context_ccs[edge_id] - if inpaint_iter == 0: - all_ecnt_cc = set() - for ecnt_id, ecnt_cc in enumerate(extend_context_ccs): - constraint_context_ids = set() - constraint_context_cc = set() - constraint_erode_context_cc = set() - tmp_mask_cc = set() - accum_context_cc = None; accum_context_cc = [] - for ecnt_node in accomp_extend_context_ccs[ecnt_id]: - if edge_maps[ecnt_node[0], ecnt_node[1]] > -1: - constraint_context_ids.add(int(round(edge_maps[ecnt_node[0], ecnt_node[1]]))) - constraint_erode_context_cc = erode_context_ccs[ecnt_id] - for constraint_context_id in constraint_context_ids: - constraint_context_cc = constraint_context_cc | context_ccs[constraint_context_id] | erode_context_ccs[constraint_context_id] - constraint_erode_context_cc = constraint_erode_context_cc | erode_context_ccs[constraint_context_id] - for i in range(background_thickness): - if i == 0: - tmp_context_nodes = copy.deepcopy(ecnt_cc) - tmp_invalid_context_nodes = copy.deepcopy(invalid_extend_edge_ccs[ecnt_id]) - tmp_mask_nodes = copy.deepcopy(accomp_extend_context_ccs[ecnt_id]) - tmp_context_map = np.zeros((mesh.graph['H'], mesh.graph['W'])).astype(np.bool) - tmp_mask_map = np.zeros((mesh.graph['H'], mesh.graph['W'])).astype(np.bool) - tmp_invalid_context_map = np.zeros((mesh.graph['H'], mesh.graph['W'])).astype(np.bool) - for node in tmp_mask_nodes: - tmp_mask_map[node[0], node[1]] = True - for node in context_ccs[ecnt_id]: - tmp_context_map[node[0], node[1]] = True - for node in erode_context_ccs[ecnt_id]: - tmp_context_map[node[0], node[1]] = True - for node in extend_context_ccs[ecnt_id]: - tmp_context_map[node[0], node[1]] = True - for node in invalid_extend_edge_ccs[ecnt_id]: - tmp_invalid_context_map[node[0], node[1]] = True - init_invalid_context_map = tmp_invalid_context_map.copy() - init_context_map = tmp - if (tmp_mask_map.astype(np.uint8) * tmp_context_map.astype(np.uint8)).max() > 0: - import pdb; pdb.set_trace() - if vis_edge_id is not None and ecnt_id == vis_edge_id: - f, ((ax1, ax2)) = plt.subplots(1, 2, sharex=True, sharey=True) - ax1.imshow(tmp_context_map * 1); ax2.imshow(init_invalid_context_map * 1 + tmp_context_map * 2) - plt.show() - import pdb; pdb.set_trace() - else: - tmp_context_nodes = new_tmp_context_nodes - new_tmp_context_nodes = None - tmp_mask_nodes = new_tmp_mask_nodes - new_tmp_mask_nodes = None - tmp_invalid_context_nodes = new_tmp_invalid_context_nodes - new_tmp_invalid_context_nodes = None - new_tmp_context_nodes = None - new_tmp_context_nodes = [] - new_tmp_invalid_context_nodes = None - new_tmp_invalid_context_nodes = [] - new_tmp_mask_nodes = set([]) - for node in tmp_context_nodes: - for ne in mesh.neighbors(node): - if ne in constraint_context_cc and \ - bool(tmp_mask_map[ne[0], ne[1]]) is False and \ - bool(tmp_context_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True: - new_tmp_context_nodes.append(ne) - tmp_context_map[ne[0], ne[1]] = True - accum_context_cc.extend(new_tmp_context_nodes) - for node in tmp_invalid_context_nodes: - for ne in mesh.neighbors(node): - if bool(tmp_mask_map[ne[0], ne[1]]) is False and \ - bool(tmp_context_map[ne[0], ne[1]]) is False and \ - bool(tmp_invalid_context_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True: - tmp_invalid_context_map[ne[0], ne[1]] = True - new_tmp_invalid_context_nodes.append(ne) - for node in tmp_mask_nodes: - for ne in mesh.neighbors(node): - if bool(tmp_mask_map[ne[0], ne[1]]) is False and \ - bool(tmp_context_map[ne[0], ne[1]]) is False and \ - bool(tmp_invalid_context_map[ne[0], ne[1]]) is False and \ - bool(forbidden_map[ne[0], ne[1]]) is True: - new_tmp_mask_nodes.add(ne) - tmp_mask_map[ne[0], ne[1]] = True - init_invalid_context_map[tmp_context_map] = False - _, tmp_label_map = cv2.connectedComponents((init_invalid_context_map | tmp_context_map).astype(np.uint8), connectivity=8) - tmp_label_ids = set(np.unique(tmp_label_map[init_invalid_context_map])) - if (tmp_mask_map.astype(np.uint8) * tmp_context_map.astype(np.uint8)).max() > 0: - import pdb; pdb.set_trace() - if vis_edge_id is not None and ecnt_id == vis_edge_id: - f, ((ax1, ax2)) = plt.subplots(1, 2, sharex=True, sharey=True) - ax1.imshow(tmp_label_map); ax2.imshow(init_invalid_context_map * 1 + tmp_context_map * 2) - plt.show() - import pdb; pdb.set_trace() - extend_context_ccs[ecnt_id] |= set(accum_context_cc) - extend_context_ccs[ecnt_id] = extend_context_ccs[ecnt_id] - mask_ccs[ecnt_id] - extend_erode_context_ccs[ecnt_id] = extend_context_ccs[ecnt_id] & constraint_erode_context_cc - extend_context_ccs[ecnt_id] = extend_context_ccs[ecnt_id] - extend_erode_context_ccs[ecnt_id] - erode_context_ccs[ecnt_id] - tmp_context_cc = context_ccs[ecnt_id] - extend_erode_context_ccs[ecnt_id] - erode_context_ccs[ecnt_id] - if len(tmp_context_cc) > 0: - context_ccs[ecnt_id] = tmp_context_cc - tmp_mask_cc = tmp_mask_cc - context_ccs[ecnt_id] - erode_context_ccs[ecnt_id] - mask_ccs[ecnt_id] = mask_ccs[ecnt_id] | tmp_mask_cc - - return context_ccs, mask_ccs, broken_mask_ccs, edge_ccs, erode_context_ccs, invalid_extend_edge_ccs, edge_maps, extend_context_ccs, extend_edge_ccs, extend_erode_context_ccs - -def DL_inpaint_edge(mesh, - info_on_pix, - config, - image, - depth, - context_ccs, - erode_context_ccs, - extend_context_ccs, - extend_erode_context_ccs, - mask_ccs, - broken_mask_ccs, - edge_ccs, - extend_edge_ccs, - init_mask_connect, - edge_maps, - rgb_model=None, - depth_edge_model=None, - depth_edge_model_init=None, - depth_feat_model=None, - specific_edge_id=-1, - specific_edge_loc=None, - inpaint_iter=0): - - if isinstance(config["gpu_ids"], int) and (config["gpu_ids"] >= 0): - device = config["gpu_ids"] - else: - device = "cpu" - - edge_map = np.zeros_like(depth) - new_edge_ccs = [set() for _ in range(len(edge_ccs))] - edge_maps_with_id = edge_maps - edge_condition = lambda x, m: m.nodes[x].get('far') is not None and len(m.nodes[x].get('far')) > 0 - edge_map = get_map_from_ccs(edge_ccs, mesh.graph['H'], mesh.graph['W'], mesh, edge_condition) - np_depth, np_image = depth.copy(), image.copy() - image_c = image.shape[-1] - image = torch.FloatTensor(image.transpose(2, 0, 1)).unsqueeze(0).to(device) - if depth.ndim < 3: - depth = depth[..., None] - depth = torch.FloatTensor(depth.transpose(2, 0, 1)).unsqueeze(0).to(device) - mesh.graph['max_edge_id'] = len(edge_ccs) - connnect_points_ccs = [set() for _ in range(len(edge_ccs))] - gp_time, tmp_mesh_time, bilateral_time = 0, 0, 0 - edges_infos = dict() - edges_in_mask = [set() for _ in range(len(edge_ccs))] - tmp_specific_edge_id = [] - for edge_id, (context_cc, mask_cc, erode_context_cc, extend_context_cc, edge_cc) in enumerate(zip(context_ccs, mask_ccs, erode_context_ccs, extend_context_ccs, edge_ccs)): - if len(specific_edge_id) > 0: - if edge_id not in specific_edge_id: - continue - if len(context_cc) < 1 or len(mask_cc) < 1: - continue - edge_dict = get_edge_from_nodes(context_cc | extend_context_cc, erode_context_cc | extend_erode_context_ccs[edge_id], mask_cc, edge_cc, extend_edge_ccs[edge_id], - mesh.graph['H'], mesh.graph['W'], mesh) - edge_dict['edge'], end_depth_maps, _ = \ - filter_irrelevant_edge_new(edge_dict['self_edge'], edge_dict['comp_edge'], - edge_map, - edge_maps_with_id, - edge_id, - edge_dict['context'], - edge_dict['depth'], mesh, context_cc | erode_context_cc | extend_context_cc | extend_erode_context_ccs[edge_id], spdb=False) - if specific_edge_loc is not None and \ - (specific_edge_loc is not None and edge_dict['mask'][specific_edge_loc[0], specific_edge_loc[1]] == 0): - continue - mask_size = get_valid_size(edge_dict['mask']) - mask_size = dilate_valid_size(mask_size, edge_dict['mask'], dilate=[20, 20]) - context_size = get_valid_size(edge_dict['context']) - context_size = dilate_valid_size(context_size, edge_dict['context'], dilate=[20, 20]) - union_size = size_operation(mask_size, context_size, operation='+') - patch_edge_dict = dict() - patch_edge_dict['mask'], patch_edge_dict['context'], patch_edge_dict['rgb'], \ - patch_edge_dict['disp'], patch_edge_dict['edge'] = \ - crop_maps_by_size(union_size, edge_dict['mask'], edge_dict['context'], - edge_dict['rgb'], edge_dict['disp'], edge_dict['edge']) - x_anchor, y_anchor = [union_size['x_min'], union_size['x_max']], [union_size['y_min'], union_size['y_max']] - tensor_edge_dict = convert2tensor(patch_edge_dict) - input_edge_feat = torch.cat((tensor_edge_dict['rgb'], - tensor_edge_dict['disp'], - tensor_edge_dict['edge'], - 1 - tensor_edge_dict['context'], - tensor_edge_dict['mask']), dim=1) - if require_depth_edge(patch_edge_dict['edge'], patch_edge_dict['mask']) and inpaint_iter == 0: - with torch.no_grad(): - depth_edge_output = depth_edge_model.forward_3P(tensor_edge_dict['mask'], - tensor_edge_dict['context'], - tensor_edge_dict['rgb'], - tensor_edge_dict['disp'], - tensor_edge_dict['edge'], - unit_length=128, - cuda=device) - depth_edge_output = depth_edge_output.cpu() - tensor_edge_dict['output'] = (depth_edge_output> config['ext_edge_threshold']).float() * tensor_edge_dict['mask'] + tensor_edge_dict['edge'] - else: - tensor_edge_dict['output'] = tensor_edge_dict['edge'] - depth_edge_output = tensor_edge_dict['edge'] + 0 - patch_edge_dict['output'] = tensor_edge_dict['output'].squeeze().data.cpu().numpy() - edge_dict['output'] = np.zeros((mesh.graph['H'], mesh.graph['W'])) - edge_dict['output'][union_size['x_min']:union_size['x_max'], union_size['y_min']:union_size['y_max']] = \ - patch_edge_dict['output'] - if require_depth_edge(patch_edge_dict['edge'], patch_edge_dict['mask']) and inpaint_iter == 0: - if ((depth_edge_output> config['ext_edge_threshold']).float() * tensor_edge_dict['mask']).max() > 0: - try: - edge_dict['fpath_map'], edge_dict['npath_map'], break_flag, npaths, fpaths, invalid_edge_id = \ - clean_far_edge_new(edge_dict['output'], end_depth_maps, edge_dict['mask'], edge_dict['context'], mesh, info_on_pix, edge_dict['self_edge'], inpaint_iter, config) - except: - import pdb; pdb.set_trace() - pre_npath_map = edge_dict['npath_map'].copy() - if config.get('repeat_inpaint_edge') is True: - for _ in range(2): - tmp_input_edge = ((edge_dict['npath_map'] > -1) + edge_dict['edge']).clip(0, 1) - patch_tmp_input_edge = crop_maps_by_size(union_size, tmp_input_edge)[0] - tensor_input_edge = torch.FloatTensor(patch_tmp_input_edge)[None, None, ...] - depth_edge_output = depth_edge_model.forward_3P(tensor_edge_dict['mask'], - tensor_edge_dict['context'], - tensor_edge_dict['rgb'], - tensor_edge_dict['disp'], - tensor_input_edge, - unit_length=128, - cuda=device) - depth_edge_output = depth_edge_output.cpu() - depth_edge_output = (depth_edge_output> config['ext_edge_threshold']).float() * tensor_edge_dict['mask'] + tensor_edge_dict['edge'] - depth_edge_output = depth_edge_output.squeeze().data.cpu().numpy() - full_depth_edge_output = np.zeros((mesh.graph['H'], mesh.graph['W'])) - full_depth_edge_output[union_size['x_min']:union_size['x_max'], union_size['y_min']:union_size['y_max']] = \ - depth_edge_output - edge_dict['fpath_map'], edge_dict['npath_map'], break_flag, npaths, fpaths, invalid_edge_id = \ - clean_far_edge_new(full_depth_edge_output, end_depth_maps, edge_dict['mask'], edge_dict['context'], mesh, info_on_pix, edge_dict['self_edge'], inpaint_iter, config) - for nid in npaths.keys(): - npath, fpath = npaths[nid], fpaths[nid] - start_mx, start_my, end_mx, end_my = -1, -1, -1, -1 - if end_depth_maps[npath[0][0], npath[0][1]] != 0: - start_mx, start_my = npath[0][0], npath[0][1] - if end_depth_maps[npath[-1][0], npath[-1][1]] != 0: - end_mx, end_my = npath[-1][0], npath[-1][1] - if start_mx == -1: - import pdb; pdb.set_trace() - valid_end_pt = () if end_mx == -1 else (end_mx, end_my, info_on_pix[(end_mx, end_my)][0]['depth']) - new_edge_info = dict(fpath=fpath, - npath=npath, - cont_end_pts=valid_end_pt, - mask_id=edge_id, - comp_edge_id=nid, - depth=end_depth_maps[start_mx, start_my]) - if edges_infos.get((start_mx, start_my)) is None: - edges_infos[(start_mx, start_my)] = [] - edges_infos[(start_mx, start_my)].append(new_edge_info) - edges_in_mask[edge_id].add((start_mx, start_my)) - if len(valid_end_pt) > 0: - new_edge_info = dict(fpath=fpath[::-1], - npath=npath[::-1], - cont_end_pts=(start_mx, start_my, info_on_pix[(start_mx, start_my)][0]['depth']), - mask_id=edge_id, - comp_edge_id=nid, - depth=end_depth_maps[end_mx, end_my]) - if edges_infos.get((end_mx, end_my)) is None: - edges_infos[(end_mx, end_my)] = [] - edges_infos[(end_mx, end_my)].append(new_edge_info) - edges_in_mask[edge_id].add((end_mx, end_my)) - for edge_id, (context_cc, mask_cc, erode_context_cc, extend_context_cc, edge_cc) in enumerate(zip(context_ccs, mask_ccs, erode_context_ccs, extend_context_ccs, edge_ccs)): - if len(specific_edge_id) > 0: - if edge_id not in specific_edge_id: - continue - if len(context_cc) < 1 or len(mask_cc) < 1: - continue - edge_dict = get_edge_from_nodes(context_cc | extend_context_cc, erode_context_cc | extend_erode_context_ccs[edge_id], mask_cc, edge_cc, extend_edge_ccs[edge_id], - mesh.graph['H'], mesh.graph['W'], mesh) - if specific_edge_loc is not None and \ - (specific_edge_loc is not None and edge_dict['mask'][specific_edge_loc[0], specific_edge_loc[1]] == 0): - continue - else: - tmp_specific_edge_id.append(edge_id) - edge_dict['edge'], end_depth_maps, _ = \ - filter_irrelevant_edge_new(edge_dict['self_edge'], edge_dict['comp_edge'], - edge_map, - edge_maps_with_id, - edge_id, - edge_dict['context'], - edge_dict['depth'], mesh, context_cc | erode_context_cc | extend_context_cc | extend_erode_context_ccs[edge_id], spdb=False) - discard_map = np.zeros_like(edge_dict['edge']) - mask_size = get_valid_size(edge_dict['mask']) - mask_size = dilate_valid_size(mask_size, edge_dict['mask'], dilate=[20, 20]) - context_size = get_valid_size(edge_dict['context']) - context_size = dilate_valid_size(context_size, edge_dict['context'], dilate=[20, 20]) - union_size = size_operation(mask_size, context_size, operation='+') - patch_edge_dict = dict() - patch_edge_dict['mask'], patch_edge_dict['context'], patch_edge_dict['rgb'], \ - patch_edge_dict['disp'], patch_edge_dict['edge'] = \ - crop_maps_by_size(union_size, edge_dict['mask'], edge_dict['context'], - edge_dict['rgb'], edge_dict['disp'], edge_dict['edge']) - x_anchor, y_anchor = [union_size['x_min'], union_size['x_max']], [union_size['y_min'], union_size['y_max']] - tensor_edge_dict = convert2tensor(patch_edge_dict) - input_edge_feat = torch.cat((tensor_edge_dict['rgb'], - tensor_edge_dict['disp'], - tensor_edge_dict['edge'], - 1 - tensor_edge_dict['context'], - tensor_edge_dict['mask']), dim=1) - edge_dict['output'] = edge_dict['edge'].copy() - - if require_depth_edge(patch_edge_dict['edge'], patch_edge_dict['mask']) and inpaint_iter == 0: - edge_dict['fpath_map'], edge_dict['npath_map'] = edge_dict['fpath_map'] * 0 - 1, edge_dict['npath_map'] * 0 - 1 - end_pts = edges_in_mask[edge_id] - for end_pt in end_pts: - cur_edge_infos = edges_infos[(end_pt[0], end_pt[1])] - cur_info = [xx for xx in cur_edge_infos if xx['mask_id'] == edge_id][0] - other_infos = [xx for xx in cur_edge_infos if xx['mask_id'] != edge_id and len(xx['cont_end_pts']) > 0] - if len(cur_info['cont_end_pts']) > 0 or (len(cur_info['cont_end_pts']) == 0 and len(other_infos) == 0): - for fnode in cur_info['fpath']: - edge_dict['fpath_map'][fnode[0], fnode[1]] = cur_info['comp_edge_id'] - for fnode in cur_info['npath']: - edge_dict['npath_map'][fnode[0], fnode[1]] = cur_info['comp_edge_id'] - fnmap = edge_dict['fpath_map'] * 1 - fnmap[edge_dict['npath_map'] != -1] = edge_dict['npath_map'][edge_dict['npath_map'] != -1] - for end_pt in end_pts: - cur_edge_infos = edges_infos[(end_pt[0], end_pt[1])] - cur_info = [xx for xx in cur_edge_infos if xx['mask_id'] == edge_id][0] - cur_depth = cur_info['depth'] - other_infos = [xx for xx in cur_edge_infos if xx['mask_id'] != edge_id and len(xx['cont_end_pts']) > 0] - comp_edge_id = cur_info['comp_edge_id'] - if len(cur_info['cont_end_pts']) == 0 and len(other_infos) > 0: - other_infos = sorted(other_infos, key=lambda aa: abs(abs(aa['cont_end_pts'][2]) - abs(cur_depth))) - for other_info in other_infos: - tmp_fmap, tmp_nmap = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1, np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1 - for fnode in other_info['fpath']: - if fnmap[fnode[0], fnode[1]] != -1: - tmp_fmap = tmp_fmap * 0 - 1 - break - else: - tmp_fmap[fnode[0], fnode[1]] = comp_edge_id - if fnmap[fnode[0], fnode[1]] != -1: - continue - for fnode in other_info['npath']: - if fnmap[fnode[0], fnode[1]] != -1: - tmp_nmap = tmp_nmap * 0 - 1 - break - else: - tmp_nmap[fnode[0], fnode[1]] = comp_edge_id - if fnmap[fnode[0], fnode[1]] != -1: - continue - break - if min(tmp_fmap.max(), tmp_nmap.max()) != -1: - edge_dict['fpath_map'] = tmp_fmap - edge_dict['fpath_map'][edge_dict['valid_area'] == 0] = -1 - edge_dict['npath_map'] = tmp_nmap - edge_dict['npath_map'][edge_dict['valid_area'] == 0] = -1 - discard_map = ((tmp_nmap != -1).astype(np.uint8) + (tmp_fmap != -1).astype(np.uint8)) * edge_dict['mask'] - else: - for fnode in cur_info['fpath']: - edge_dict['fpath_map'][fnode[0], fnode[1]] = cur_info['comp_edge_id'] - for fnode in cur_info['npath']: - edge_dict['npath_map'][fnode[0], fnode[1]] = cur_info['comp_edge_id'] - if edge_dict['npath_map'].min() == 0 or edge_dict['fpath_map'].min() == 0: - import pdb; pdb.set_trace() - edge_dict['output'] = (edge_dict['npath_map'] > -1) * edge_dict['mask'] + edge_dict['context'] * edge_dict['edge'] - mesh, _, _, _ = create_placeholder(edge_dict['context'], edge_dict['mask'], - edge_dict['depth'], edge_dict['fpath_map'], - edge_dict['npath_map'], mesh, inpaint_iter, - edge_ccs, - extend_edge_ccs[edge_id], - edge_maps_with_id, - edge_id) - - dxs, dys = np.where(discard_map != 0) - for dx, dy in zip(dxs, dys): - mesh.nodes[(dx, dy)]['inpaint_twice'] = False - depth_dict = depth_inpainting(context_cc, extend_context_cc, erode_context_cc | extend_erode_context_ccs[edge_id], mask_cc, mesh, config, union_size, depth_feat_model, edge_dict['output']) - refine_depth_output = depth_dict['output']*depth_dict['mask'] - for near_id in np.unique(edge_dict['npath_map'])[1:]: - refine_depth_output = refine_depth_around_edge(refine_depth_output.copy(), - (edge_dict['fpath_map'] == near_id).astype(np.uint8) * edge_dict['mask'], - (edge_dict['fpath_map'] == near_id).astype(np.uint8), - (edge_dict['npath_map'] == near_id).astype(np.uint8) * edge_dict['mask'], - depth_dict['mask'].copy(), - depth_dict['output'] * depth_dict['context'], - config) - depth_dict['output'][depth_dict['mask'] > 0] = refine_depth_output[depth_dict['mask'] > 0] - rgb_dict = get_rgb_from_nodes(context_cc | extend_context_cc, - erode_context_cc | extend_erode_context_ccs[edge_id], mask_cc, mesh.graph['H'], mesh.graph['W'], mesh) - if np.all(rgb_dict['mask'] == edge_dict['mask']) is False: - import pdb; pdb.set_trace() - rgb_dict['edge'] = edge_dict['output'] - patch_rgb_dict = dict() - patch_rgb_dict['mask'], patch_rgb_dict['context'], patch_rgb_dict['rgb'], \ - patch_rgb_dict['edge'] = crop_maps_by_size(union_size, rgb_dict['mask'], - rgb_dict['context'], rgb_dict['rgb'], - rgb_dict['edge']) - tensor_rgb_dict = convert2tensor(patch_rgb_dict) - resize_rgb_dict = {k: v.clone() for k, v in tensor_rgb_dict.items()} - max_hw = np.array([*patch_rgb_dict['mask'].shape[-2:]]).max() - init_frac = config['largest_size'] / (np.array([*patch_rgb_dict['mask'].shape[-2:]]).prod() ** 0.5) - resize_hw = [patch_rgb_dict['mask'].shape[-2] * init_frac, patch_rgb_dict['mask'].shape[-1] * init_frac] - resize_max_hw = max(resize_hw) - frac = (np.floor(resize_max_hw / 128.) * 128.) / max_hw - if frac < 1: - resize_mark = torch.nn.functional.interpolate(torch.cat((resize_rgb_dict['mask'], - resize_rgb_dict['context']), - dim=1), - scale_factor=frac, - mode='area') - resize_rgb_dict['mask'] = (resize_mark[:, 0:1] > 0).float() - resize_rgb_dict['context'] = (resize_mark[:, 1:2] == 1).float() - resize_rgb_dict['context'][resize_rgb_dict['mask'] > 0] = 0 - resize_rgb_dict['rgb'] = torch.nn.functional.interpolate(resize_rgb_dict['rgb'], - scale_factor=frac, - mode='area') - resize_rgb_dict['rgb'] = resize_rgb_dict['rgb'] * resize_rgb_dict['context'] - resize_rgb_dict['edge'] = torch.nn.functional.interpolate(resize_rgb_dict['edge'], - scale_factor=frac, - mode='area') - resize_rgb_dict['edge'] = (resize_rgb_dict['edge'] > 0).float() * 0 - resize_rgb_dict['edge'] = resize_rgb_dict['edge'] * (resize_rgb_dict['context'] + resize_rgb_dict['mask']) - rgb_input_feat = torch.cat((resize_rgb_dict['rgb'], resize_rgb_dict['edge']), dim=1) - rgb_input_feat[:, 3] = 1 - rgb_input_feat[:, 3] - resize_mask = open_small_mask(resize_rgb_dict['mask'], resize_rgb_dict['context'], 3, 41) - specified_hole = resize_mask - with torch.no_grad(): - rgb_output = rgb_model.forward_3P(specified_hole, - resize_rgb_dict['context'], - resize_rgb_dict['rgb'], - resize_rgb_dict['edge'], - unit_length=128, - cuda=device) - rgb_output = rgb_output.cpu() - if config.get('gray_image') is True: - rgb_output = rgb_output.mean(1, keepdim=True).repeat((1,3,1,1)) - rgb_output = rgb_output.cpu() - resize_rgb_dict['output'] = rgb_output * resize_rgb_dict['mask'] + resize_rgb_dict['rgb'] - tensor_rgb_dict['output'] = resize_rgb_dict['output'] - if frac < 1: - tensor_rgb_dict['output'] = torch.nn.functional.interpolate(tensor_rgb_dict['output'], - size=tensor_rgb_dict['mask'].shape[-2:], - mode='bicubic') - tensor_rgb_dict['output'] = tensor_rgb_dict['output'] * \ - tensor_rgb_dict['mask'] + (tensor_rgb_dict['rgb'] * tensor_rgb_dict['context']) - patch_rgb_dict['output'] = tensor_rgb_dict['output'].data.cpu().numpy().squeeze().transpose(1,2,0) - rgb_dict['output'] = np.zeros((mesh.graph['H'], mesh.graph['W'], 3)) - rgb_dict['output'][union_size['x_min']:union_size['x_max'], union_size['y_min']:union_size['y_max']] = \ - patch_rgb_dict['output'] - - if require_depth_edge(patch_edge_dict['edge'], patch_edge_dict['mask']) or inpaint_iter > 0: - edge_occlusion = True - else: - edge_occlusion = False - for node in erode_context_cc: - if rgb_dict['mask'][node[0], node[1]] > 0: - for info in info_on_pix[(node[0], node[1])]: - if abs(info['depth']) == abs(node[2]): - info['update_color'] = (rgb_dict['output'][node[0], node[1]] * 255).astype(np.uint8) - if frac < 1.: - depth_edge_dilate_2_color_flag = False - else: - depth_edge_dilate_2_color_flag = True - hxs, hys = np.where((rgb_dict['mask'] > 0) & (rgb_dict['erode'] == 0)) - for hx, hy in zip(hxs, hys): - real_depth = None - if abs(depth_dict['output'][hx, hy]) <= abs(np_depth[hx, hy]): - depth_dict['output'][hx, hy] = np_depth[hx, hy] + 0.01 - node = (hx, hy, -depth_dict['output'][hx, hy]) - if info_on_pix.get((node[0], node[1])) is not None: - for info in info_on_pix.get((node[0], node[1])): - if info.get('inpaint_id') is None or abs(info['inpaint_id'] < mesh.nodes[(hx, hy)]['inpaint_id']): - pre_depth = info['depth'] if info.get('real_depth') is None else info['real_depth'] - if abs(node[2]) < abs(pre_depth): - node = (node[0], node[1], -(abs(pre_depth) + 0.001)) - if mesh.has_node(node): - real_depth = node[2] - while True: - if mesh.has_node(node): - node = (node[0], node[1], -(abs(node[2]) + 0.001)) - else: - break - if real_depth == node[2]: - real_depth = None - cur_disp = 1./node[2] - if not(mesh.has_node(node)): - if not mesh.has_node((node[0], node[1])): - print("2D node not found.") - import pdb; pdb.set_trace() - if inpaint_iter == 1: - paint = (rgb_dict['output'][hx, hy] * 255).astype(np.uint8) - else: - paint = (rgb_dict['output'][hx, hy] * 255).astype(np.uint8) - ndict = dict(color=paint, - synthesis=True, - disp=cur_disp, - cc_id=set([edge_id]), - overlap_number=1.0, - refine_depth=False, - edge_occlusion=edge_occlusion, - depth_edge_dilate_2_color_flag=depth_edge_dilate_2_color_flag, - real_depth=real_depth) - mesh, _, _ = refresh_node((node[0], node[1]), mesh.nodes[(node[0], node[1])], node, ndict, mesh, stime=True) - if inpaint_iter == 0 and mesh.degree(node) < 4: - connnect_points_ccs[edge_id].add(node) - if info_on_pix.get((hx, hy)) is None: - info_on_pix[(hx, hy)] = [] - new_info = {'depth':node[2], - 'color': paint, - 'synthesis':True, - 'disp':cur_disp, - 'cc_id':set([edge_id]), - 'inpaint_id':inpaint_iter + 1, - 'edge_occlusion':edge_occlusion, - 'overlap_number':1.0, - 'real_depth': real_depth} - info_on_pix[(hx, hy)].append(new_info) - specific_edge_id = tmp_specific_edge_id - for erode_id, erode_context_cc in enumerate(erode_context_ccs): - if len(specific_edge_id) > 0 and erode_id not in specific_edge_id: - continue - for erode_node in erode_context_cc: - for info in info_on_pix[(erode_node[0], erode_node[1])]: - if info['depth'] == erode_node[2]: - info['color'] = info['update_color'] - mesh.nodes[erode_node]['color'] = info['update_color'] - np_image[(erode_node[0], erode_node[1])] = info['update_color'] - new_edge_ccs = [set() for _ in range(mesh.graph['max_edge_id'] + 1)] - for node in mesh.nodes: - if len(node) == 2: - mesh.remove_node(node) - continue - if mesh.nodes[node].get('edge_id') is not None and mesh.nodes[node].get('inpaint_id') == inpaint_iter + 1: - if mesh.nodes[node].get('inpaint_twice') is False: - continue - try: - new_edge_ccs[mesh.nodes[node].get('edge_id')].add(node) - except: - import pdb; pdb.set_trace() - specific_mask_nodes = None - if inpaint_iter == 0: - mesh, info_on_pix = refine_color_around_edge(mesh, info_on_pix, new_edge_ccs, config, False) - - return mesh, info_on_pix, specific_mask_nodes, new_edge_ccs, connnect_points_ccs, np_image - - -def write_ply(image, - depth, - int_mtx, - ply_name, - config, - rgb_model, - depth_edge_model, - depth_edge_model_init, - depth_feat_model): - depth = depth.astype(np.float64) - input_mesh, xy2depth, image, depth = create_mesh(depth, image, int_mtx, config) - - H, W = input_mesh.graph['H'], input_mesh.graph['W'] - input_mesh = tear_edges(input_mesh, config['depth_threshold'], xy2depth) - input_mesh, info_on_pix = generate_init_node(input_mesh, config, min_node_in_cc=200) - edge_ccs, input_mesh, edge_mesh = group_edges(input_mesh, config, image, remove_conflict_ordinal=False) - edge_canvas = np.zeros((H, W)) - 1 - - input_mesh, info_on_pix, depth = reassign_floating_island(input_mesh, info_on_pix, image, depth) - input_mesh = update_status(input_mesh, info_on_pix) - specific_edge_id = [] - edge_ccs, input_mesh, edge_mesh = group_edges(input_mesh, config, image, remove_conflict_ordinal=True) - pre_depth = depth.copy() - input_mesh, info_on_pix, edge_mesh, depth, aft_mark = remove_dangling(input_mesh, edge_ccs, edge_mesh, info_on_pix, image, depth, config) - - input_mesh, depth, info_on_pix = update_status(input_mesh, info_on_pix, depth) - edge_ccs, input_mesh, edge_mesh = group_edges(input_mesh, config, image, remove_conflict_ordinal=True) - edge_canvas = np.zeros((H, W)) - 1 - - mesh, info_on_pix, depth = fill_missing_node(input_mesh, info_on_pix, image, depth) - if config['extrapolate_border'] is True: - pre_depth = depth.copy() - input_mesh, info_on_pix, depth = refresh_bord_depth(input_mesh, info_on_pix, image, depth) - input_mesh = remove_node_feat(input_mesh, 'edge_id') - aft_depth = depth.copy() - input_mesh, info_on_pix, depth, image = enlarge_border(input_mesh, info_on_pix, depth, image, config) - noext_H, noext_W = H, W - H, W = image.shape[:2] - input_mesh, info_on_pix = fill_dummy_bord(input_mesh, info_on_pix, image, depth, config) - edge_ccs, input_mesh, edge_mesh = \ - group_edges(input_mesh, config, image, remove_conflict_ordinal=True) - input_mesh = combine_end_node(input_mesh, edge_mesh, edge_ccs, depth) - input_mesh, depth, info_on_pix = update_status(input_mesh, info_on_pix, depth) - edge_ccs, input_mesh, edge_mesh = \ - group_edges(input_mesh, config, image, remove_conflict_ordinal=True, spdb=False) - input_mesh = remove_redundant_edge(input_mesh, edge_mesh, edge_ccs, info_on_pix, config, redundant_number=config['redundant_number'], spdb=False) - input_mesh, depth, info_on_pix = update_status(input_mesh, info_on_pix, depth) - edge_ccs, input_mesh, edge_mesh = group_edges(input_mesh, config, image, remove_conflict_ordinal=True) - input_mesh = combine_end_node(input_mesh, edge_mesh, edge_ccs, depth) - input_mesh = remove_redundant_edge(input_mesh, edge_mesh, edge_ccs, info_on_pix, config, redundant_number=config['redundant_number'], invalid=True, spdb=False) - input_mesh, depth, info_on_pix = update_status(input_mesh, info_on_pix, depth) - edge_ccs, input_mesh, edge_mesh = group_edges(input_mesh, config, image, remove_conflict_ordinal=True) - input_mesh = combine_end_node(input_mesh, edge_mesh, edge_ccs, depth) - input_mesh, depth, info_on_pix = update_status(input_mesh, info_on_pix, depth) - edge_ccs, input_mesh, edge_mesh = group_edges(input_mesh, config, image, remove_conflict_ordinal=True) - edge_condition = lambda x, m: m.nodes[x].get('far') is not None and len(m.nodes[x].get('far')) > 0 - edge_map = get_map_from_ccs(edge_ccs, input_mesh.graph['H'], input_mesh.graph['W'], input_mesh, edge_condition) - other_edge_with_id = get_map_from_ccs(edge_ccs, input_mesh.graph['H'], input_mesh.graph['W'], real_id=True) - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="up") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="left") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="down") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="right") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="right-up") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="right-down") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="left-up") - info_on_pix, input_mesh, image, depth, edge_ccs = extrapolate(input_mesh, info_on_pix, image, depth, other_edge_with_id, edge_map, edge_ccs, - depth_edge_model, depth_feat_model, rgb_model, config, direc="left-down") - specific_edge_loc = None - specific_edge_id = [] - vis_edge_id = None - context_ccs, mask_ccs, broken_mask_ccs, edge_ccs, erode_context_ccs, \ - init_mask_connect, edge_maps, extend_context_ccs, extend_edge_ccs, extend_erode_context_ccs = \ - context_and_holes(input_mesh, - edge_ccs, - config, - specific_edge_id, - specific_edge_loc, - depth_feat_model, - inpaint_iter=0, - vis_edge_id=vis_edge_id) - edge_canvas = np.zeros((H, W)) - mask = np.zeros((H, W)) - context = np.zeros((H, W)) - vis_edge_ccs = filter_edge(input_mesh, edge_ccs, config) - edge_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - 1 - specific_edge_loc = None - FG_edge_maps = edge_maps.copy() - edge_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - 1 - # for cc_id, cc in enumerate(edge_ccs): - # for node in cc: - # edge_canvas[node[0], node[1]] = cc_id - # f, ((ax0, ax1, ax2)) = plt.subplots(1, 3, sharex=True, sharey=True); ax0.imshow(1./depth); ax1.imshow(image); ax2.imshow(edge_canvas); plt.show() - input_mesh, info_on_pix, specific_edge_nodes, new_edge_ccs, connect_points_ccs, image = DL_inpaint_edge(input_mesh, - info_on_pix, - config, - image, - depth, - context_ccs, - erode_context_ccs, - extend_context_ccs, - extend_erode_context_ccs, - mask_ccs, - broken_mask_ccs, - edge_ccs, - extend_edge_ccs, - init_mask_connect, - edge_maps, - rgb_model, - depth_edge_model, - depth_edge_model_init, - depth_feat_model, - specific_edge_id, - specific_edge_loc, - inpaint_iter=0) - specific_edge_id = [] - edge_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - connect_points_ccs = [set() for _ in connect_points_ccs] - context_ccs, mask_ccs, broken_mask_ccs, edge_ccs, erode_context_ccs, init_mask_connect, \ - edge_maps, extend_context_ccs, extend_edge_ccs, extend_erode_context_ccs = \ - context_and_holes(input_mesh, new_edge_ccs, config, specific_edge_id, specific_edge_loc, depth_feat_model, connect_points_ccs, inpaint_iter=1) - mask_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - context_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - erode_context_ccs_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - edge_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - # edge_canvas = np.zeros((input_mesh.graph['H'], input_mesh.graph['W'])) - 1 - # for cc_id, cc in enumerate(edge_ccs): - # for node in cc: - # edge_canvas[node[0], node[1]] = cc_id - specific_edge_id = [] - input_mesh, info_on_pix, specific_edge_nodes, new_edge_ccs, _, image = DL_inpaint_edge(input_mesh, - info_on_pix, - config, - image, - depth, - context_ccs, - erode_context_ccs, - extend_context_ccs, - extend_erode_context_ccs, - mask_ccs, - broken_mask_ccs, - edge_ccs, - extend_edge_ccs, - init_mask_connect, - edge_maps, - rgb_model, - depth_edge_model, - depth_edge_model_init, - depth_feat_model, - specific_edge_id, - specific_edge_loc, - inpaint_iter=1) - vertex_id = 0 - input_mesh.graph['H'], input_mesh.graph['W'] = input_mesh.graph['noext_H'], input_mesh.graph['noext_W'] - background_canvas = np.zeros((input_mesh.graph['H'], - input_mesh.graph['W'], - 3)) - ply_flag = config.get('save_ply') - if ply_flag is True: - node_str_list = [] - else: - node_str_color = [] - node_str_point = [] - out_fmt = lambda x, x_flag: str(x) if x_flag is True else x - point_time = 0 - hlight_time = 0 - cur_id_time = 0 - node_str_time = 0 - generate_face_time = 0 - point_list = [] - k_00, k_02, k_11, k_12 = \ - input_mesh.graph['cam_param_pix_inv'][0, 0], input_mesh.graph['cam_param_pix_inv'][0, 2], \ - input_mesh.graph['cam_param_pix_inv'][1, 1], input_mesh.graph['cam_param_pix_inv'][1, 2] - w_offset = input_mesh.graph['woffset'] - h_offset = input_mesh.graph['hoffset'] - for pix_xy, pix_list in info_on_pix.items(): - for pix_idx, pix_info in enumerate(pix_list): - pix_depth = pix_info['depth'] if pix_info.get('real_depth') is None else pix_info['real_depth'] - str_pt = [out_fmt(x, ply_flag) for x in reproject_3d_int_detail(pix_xy[0], pix_xy[1], pix_depth, - k_00, k_02, k_11, k_12, w_offset, h_offset)] - if input_mesh.has_node((pix_xy[0], pix_xy[1], pix_info['depth'])) is False: - return False - continue - if pix_info.get('overlap_number') is not None: - str_color = [out_fmt(x, ply_flag) for x in (pix_info['color']/pix_info['overlap_number']).astype(np.uint8).tolist()] - else: - str_color = [out_fmt(x, ply_flag) for x in pix_info['color'].tolist()] - if pix_info.get('edge_occlusion') is True: - str_color.append(out_fmt(4, ply_flag)) - else: - if pix_info.get('inpaint_id') is None: - str_color.append(out_fmt(1, ply_flag)) - else: - str_color.append(out_fmt(pix_info.get('inpaint_id') + 1, ply_flag)) - if pix_info.get('modified_border') is True or pix_info.get('ext_pixel') is True: - if len(str_color) == 4: - str_color[-1] = out_fmt(5, ply_flag) - else: - str_color.append(out_fmt(5, ply_flag)) - pix_info['cur_id'] = vertex_id - input_mesh.nodes[(pix_xy[0], pix_xy[1], pix_info['depth'])]['cur_id'] = out_fmt(vertex_id, ply_flag) - vertex_id += 1 - if ply_flag is True: - node_str_list.append(' '.join(str_pt) + ' ' + ' '.join(str_color) + '\n') - else: - node_str_color.append(str_color) - node_str_point.append(str_pt) - str_faces = generate_face(input_mesh, info_on_pix, config) - if config['save_ply'] is True: - print("Writing mesh file %s ..." % ply_name) - with open(ply_name, 'w') as ply_fi: - ply_fi.write('ply\n' + 'format ascii 1.0\n') - ply_fi.write('comment H ' + str(int(input_mesh.graph['H'])) + '\n') - ply_fi.write('comment W ' + str(int(input_mesh.graph['W'])) + '\n') - ply_fi.write('comment hFov ' + str(float(input_mesh.graph['hFov'])) + '\n') - ply_fi.write('comment vFov ' + str(float(input_mesh.graph['vFov'])) + '\n') - ply_fi.write('element vertex ' + str(len(node_str_list)) + '\n') - ply_fi.write('property float x\n' + \ - 'property float y\n' + \ - 'property float z\n' + \ - 'property uchar red\n' + \ - 'property uchar green\n' + \ - 'property uchar blue\n' + \ - 'property uchar alpha\n') - ply_fi.write('element face ' + str(len(str_faces)) + '\n') - ply_fi.write('property list uchar int vertex_index\n') - ply_fi.write('end_header\n') - ply_fi.writelines(node_str_list) - ply_fi.writelines(str_faces) - ply_fi.close() - return input_mesh - else: - H = int(input_mesh.graph['H']) - W = int(input_mesh.graph['W']) - hFov = input_mesh.graph['hFov'] - vFov = input_mesh.graph['vFov'] - node_str_color = np.array(node_str_color).astype(np.float32) - node_str_color[..., :3] = node_str_color[..., :3] / 255. - node_str_point = np.array(node_str_point) - str_faces = np.array(str_faces) - - return node_str_point, node_str_color, str_faces, H, W, hFov, vFov - -def read_ply(mesh_fi): - ply_fi = open(mesh_fi, 'r') - Height = None - Width = None - hFov = None - vFov = None - while True: - line = ply_fi.readline().split('\n')[0] - if line.startswith('element vertex'): - num_vertex = int(line.split(' ')[-1]) - elif line.startswith('element face'): - num_face = int(line.split(' ')[-1]) - elif line.startswith('comment'): - if line.split(' ')[1] == 'H': - Height = int(line.split(' ')[-1].split('\n')[0]) - if line.split(' ')[1] == 'W': - Width = int(line.split(' ')[-1].split('\n')[0]) - if line.split(' ')[1] == 'hFov': - hFov = float(line.split(' ')[-1].split('\n')[0]) - if line.split(' ')[1] == 'vFov': - vFov = float(line.split(' ')[-1].split('\n')[0]) - elif line.startswith('end_header'): - break - contents = ply_fi.readlines() - vertex_infos = contents[:num_vertex] - face_infos = contents[num_vertex:] - verts = [] - colors = [] - faces = [] - for v_info in vertex_infos: - str_info = [float(v) for v in v_info.split('\n')[0].split(' ')] - if len(str_info) == 6: - vx, vy, vz, r, g, b = str_info - else: - vx, vy, vz, r, g, b, hi = str_info - verts.append([vx, vy, vz]) - colors.append([r, g, b, hi]) - verts = np.array(verts) - try: - colors = np.array(colors) - colors[..., :3] = colors[..., :3]/255. - except: - import pdb - pdb.set_trace() - - for f_info in face_infos: - _, v1, v2, v3 = [int(f) for f in f_info.split('\n')[0].split(' ')] - faces.append([v1, v2, v3]) - faces = np.array(faces) - - - return verts, colors, faces, Height, Width, hFov, vFov - - -class Canvas_view(): - def __init__(self, - fov, - verts, - faces, - colors, - canvas_size, - factor=1, - bgcolor='gray', - proj='perspective', - ): - self.canvas = scene.SceneCanvas(bgcolor=bgcolor, size=(canvas_size*factor, canvas_size*factor)) - self.view = self.canvas.central_widget.add_view() - self.view.camera = 'perspective' - self.view.camera.fov = fov - self.mesh = visuals.Mesh(shading=None) - self.mesh.attach(Alpha(1.0)) - self.view.add(self.mesh) - self.tr = self.view.camera.transform - self.mesh.set_data(vertices=verts, faces=faces, vertex_colors=colors[:, :3]) - self.translate([0,0,0]) - self.rotate(axis=[1,0,0], angle=180) - self.view_changed() - - def translate(self, trans=[0,0,0]): - self.tr.translate(trans) - - def rotate(self, axis=[1,0,0], angle=0): - self.tr.rotate(axis=axis, angle=angle) - - def view_changed(self): - self.view.camera.view_changed() - - def render(self): - return self.canvas.render() - - def reinit_mesh(self, verts, faces, colors): - self.mesh.set_data(vertices=verts, faces=faces, vertex_colors=colors[:, :3]) - - def reinit_camera(self, fov): - self.view.camera.fov = fov - self.view.camera.view_changed() - - -def output_3d_photo(verts, colors, faces, Height, Width, hFov, vFov, tgt_poses, video_traj_types, ref_pose, - output_dir, ref_image, int_mtx, config, image, videos_poses, video_basename, original_H=None, original_W=None, - border=None, depth=None, normal_canvas=None, all_canvas=None, mean_loc_depth=None): - - cam_mesh = netx.Graph() - cam_mesh.graph['H'] = Height - cam_mesh.graph['W'] = Width - cam_mesh.graph['original_H'] = original_H - cam_mesh.graph['original_W'] = original_W - int_mtx_real_x = int_mtx[0] * Width - int_mtx_real_y = int_mtx[1] * Height - cam_mesh.graph['hFov'] = 2 * np.arctan((1. / 2.) * ((cam_mesh.graph['original_W']) / int_mtx_real_x[0])) - cam_mesh.graph['vFov'] = 2 * np.arctan((1. / 2.) * ((cam_mesh.graph['original_H']) / int_mtx_real_y[1])) - colors = colors[..., :3] - - fov_in_rad = max(cam_mesh.graph['vFov'], cam_mesh.graph['hFov']) - fov = (fov_in_rad * 180 / np.pi) - print("fov: " + str(fov)) - init_factor = 1 - if config.get('anti_flickering') is True: - init_factor = 3 - if (cam_mesh.graph['original_H'] is not None) and (cam_mesh.graph['original_W'] is not None): - canvas_w = cam_mesh.graph['original_W'] - canvas_h = cam_mesh.graph['original_H'] - else: - canvas_w = cam_mesh.graph['W'] - canvas_h = cam_mesh.graph['H'] - canvas_size = max(canvas_h, canvas_w) - if normal_canvas is None: - normal_canvas = Canvas_view(fov, - verts, - faces, - colors, - canvas_size=canvas_size, - factor=init_factor, - bgcolor='gray', - proj='perspective') - else: - normal_canvas.reinit_mesh(verts, faces, colors) - normal_canvas.reinit_camera(fov) - img = normal_canvas.render() - backup_img, backup_all_img, all_img_wo_bound = img.copy(), img.copy() * 0, img.copy() * 0 - img = cv2.resize(img, (int(img.shape[1] / init_factor), int(img.shape[0] / init_factor)), interpolation=cv2.INTER_AREA) - if border is None: - border = [0, img.shape[0], 0, img.shape[1]] - H, W = cam_mesh.graph['H'], cam_mesh.graph['W'] - if (cam_mesh.graph['original_H'] is not None) and (cam_mesh.graph['original_W'] is not None): - aspect_ratio = cam_mesh.graph['original_H'] / cam_mesh.graph['original_W'] - else: - aspect_ratio = cam_mesh.graph['H'] / cam_mesh.graph['W'] - if aspect_ratio > 1: - img_h_len = cam_mesh.graph['H'] if cam_mesh.graph.get('original_H') is None else cam_mesh.graph['original_H'] - img_w_len = img_h_len / aspect_ratio - anchor = [0, - img.shape[0], - int(max(0, int((img.shape[1])//2 - img_w_len//2))), - int(min(int((img.shape[1])//2 + img_w_len//2), (img.shape[1])-1))] - elif aspect_ratio <= 1: - img_w_len = cam_mesh.graph['W'] if cam_mesh.graph.get('original_W') is None else cam_mesh.graph['original_W'] - img_h_len = img_w_len * aspect_ratio - anchor = [int(max(0, int((img.shape[0])//2 - img_h_len//2))), - int(min(int((img.shape[0])//2 + img_h_len//2), (img.shape[0])-1)), - 0, - img.shape[1]] - anchor = np.array(anchor) - plane_width = np.tan(fov_in_rad/2.) * np.abs(mean_loc_depth) - for video_pose, video_traj_type in zip(videos_poses, video_traj_types): - stereos = [] - tops = []; buttoms = []; lefts = []; rights = [] - for tp_id, tp in enumerate(video_pose): - rel_pose = np.linalg.inv(np.dot(tp, np.linalg.inv(ref_pose))) - axis, angle = transforms3d.axangles.mat2axangle(rel_pose[0:3, 0:3]) - normal_canvas.rotate(axis=axis, angle=(angle*180)/np.pi) - normal_canvas.translate(rel_pose[:3,3]) - new_mean_loc_depth = mean_loc_depth - float(rel_pose[2, 3]) - if 'dolly' in video_traj_type: - new_fov = float((np.arctan2(plane_width, np.array([np.abs(new_mean_loc_depth)])) * 180. / np.pi) * 2) - normal_canvas.reinit_camera(new_fov) - else: - normal_canvas.reinit_camera(fov) - normal_canvas.view_changed() - img = normal_canvas.render() - img = cv2.GaussianBlur(img,(int(init_factor//2 * 2 + 1), int(init_factor//2 * 2 + 1)), 0) - img = cv2.resize(img, (int(img.shape[1] / init_factor), int(img.shape[0] / init_factor)), interpolation=cv2.INTER_AREA) - img = img[anchor[0]:anchor[1], anchor[2]:anchor[3]] - img = img[int(border[0]):int(border[1]), int(border[2]):int(border[3])] - - if any(np.array(config['crop_border']) > 0.0): - H_c, W_c, _ = img.shape - o_t = int(H_c * config['crop_border'][0]) - o_l = int(W_c * config['crop_border'][1]) - o_b = int(H_c * config['crop_border'][2]) - o_r = int(W_c * config['crop_border'][3]) - img = img[o_t:H_c-o_b, o_l:W_c-o_r] - img = cv2.resize(img, (W_c, H_c), interpolation=cv2.INTER_CUBIC) - - """ - img = cv2.resize(img, (int(img.shape[1] / init_factor), int(img.shape[0] / init_factor)), interpolation=cv2.INTER_CUBIC) - img = img[anchor[0]:anchor[1], anchor[2]:anchor[3]] - img = img[int(border[0]):int(border[1]), int(border[2]):int(border[3])] - - if config['crop_border'] is True: - top, buttom, left, right = find_largest_rect(img, bg_color=(128, 128, 128)) - tops.append(top); buttoms.append(buttom); lefts.append(left); rights.append(right) - """ - stereos.append(img[..., :3]) - normal_canvas.translate(-rel_pose[:3,3]) - normal_canvas.rotate(axis=axis, angle=-(angle*180)/np.pi) - normal_canvas.view_changed() - """ - if config['crop_border'] is True: - atop, abuttom = min(max(tops), img.shape[0]//2 - 10), max(min(buttoms), img.shape[0]//2 + 10) - aleft, aright = min(max(lefts), img.shape[1]//2 - 10), max(min(rights), img.shape[1]//2 + 10) - atop -= atop % 2; abuttom -= abuttom % 2; aleft -= aleft % 2; aright -= aright % 2 - else: - atop = 0; abuttom = img.shape[0] - img.shape[0] % 2; aleft = 0; aright = img.shape[1] - img.shape[1] % 2 - """ - atop = 0; abuttom = img.shape[0] - img.shape[0] % 2; aleft = 0; aright = img.shape[1] - img.shape[1] % 2 - crop_stereos = [] - for stereo in stereos: - crop_stereos.append((stereo[atop:abuttom, aleft:aright, :3] * 1).astype(np.uint8)) - stereos = crop_stereos - clip = ImageSequenceClip(stereos, fps=config['fps']) - if isinstance(video_basename, list): - video_basename = video_basename[0] - clip.write_videofile(os.path.join(output_dir, video_basename + '_' + video_traj_type + '.mp4'), fps=config['fps']) - - - - return normal_canvas, all_canvas diff --git a/spaces/Kartik2192/Abcd/README.md b/spaces/Kartik2192/Abcd/README.md deleted file mode 100644 index 6a3bb8328293bd3fe6ce639653fba22487b9e1bb..0000000000000000000000000000000000000000 --- a/spaces/Kartik2192/Abcd/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Abcd -emoji: 👀 -colorFrom: red -colorTo: blue -sdk: static -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Kedreamix/YoloGesture/utils/utils_fit.py b/spaces/Kedreamix/YoloGesture/utils/utils_fit.py deleted file mode 100644 index 68f54200f8860b1cd8c8d6493b13d6f18afdde72..0000000000000000000000000000000000000000 --- a/spaces/Kedreamix/YoloGesture/utils/utils_fit.py +++ /dev/null @@ -1,128 +0,0 @@ -import os - -import torch -from tqdm import tqdm - -from utils.utils import get_lr - - -def fit_one_epoch(model_train, model, yolo_loss, loss_history, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda, fp16, scaler, save_period, save_dir, local_rank=0): - loss = 0 - val_loss = 0 - - if local_rank == 0: - print('Start Train') - pbar = tqdm(total=epoch_step,desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) - model_train.train() - for iteration, batch in enumerate(gen): - if iteration >= epoch_step: - break - - images, targets = batch[0], batch[1] - with torch.no_grad(): - if cuda: - images = images.cuda() - targets = [ann.cuda() for ann in targets] - #----------------------# - # 清零梯度 - #----------------------# - optimizer.zero_grad() - if not fp16: - #----------------------# - # 前向传播 - #----------------------# - outputs = model_train(images) - - loss_value_all = 0 - #----------------------# - # 计算损失 - #----------------------# - for l in range(len(outputs)): - loss_item = yolo_loss(l, outputs[l], targets) - loss_value_all += loss_item - loss_value = loss_value_all - - #----------------------# - # 反向传播 - #----------------------# - loss_value.backward() - optimizer.step() - else: - from torch.cuda.amp import autocast - with autocast(): - #----------------------# - # 前向传播 - #----------------------# - outputs = model_train(images) - - loss_value_all = 0 - #----------------------# - # 计算损失 - #----------------------# - for l in range(len(outputs)): - loss_item = yolo_loss(l, outputs[l], targets) - loss_value_all += loss_item - loss_value = loss_value_all - - #----------------------# - # 反向传播 - #----------------------# - scaler.scale(loss_value).backward() - scaler.step(optimizer) - scaler.update() - - loss += loss_value.item() - - if local_rank == 0: - pbar.set_postfix(**{'loss' : loss / (iteration + 1), - 'lr' : get_lr(optimizer)}) - pbar.update(1) - - if local_rank == 0: - pbar.close() - print('Finish Train') - print('Start Validation') - pbar = tqdm(total=epoch_step_val, desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) - - model_train.eval() - for iteration, batch in enumerate(gen_val): - if iteration >= epoch_step_val: - break - images, targets = batch[0], batch[1] - with torch.no_grad(): - if cuda: - images = images.cuda() - targets = [ann.cuda() for ann in targets] - #----------------------# - # 清零梯度 - #----------------------# - optimizer.zero_grad() - #----------------------# - # 前向传播 - #----------------------# - outputs = model_train(images) - - loss_value_all = 0 - #----------------------# - # 计算损失 - #----------------------# - for l in range(len(outputs)): - loss_item = yolo_loss(l, outputs[l], targets) - loss_value_all += loss_item - loss_value = loss_value_all - - val_loss += loss_value.item() - if local_rank == 0: - pbar.set_postfix(**{'val_loss': val_loss / (iteration + 1)}) - pbar.update(1) - - if local_rank == 0: - pbar.close() - print('Finish Validation') - loss_history.append_loss(epoch + 1, loss / epoch_step, val_loss / epoch_step_val) - print('Epoch:'+ str(epoch + 1) + '/' + str(Epoch)) - print('Total Loss: %.3f || Val Loss: %.3f ' % (loss / epoch_step, val_loss / epoch_step_val)) - if (epoch + 1) % save_period == 0 or epoch + 1 == Epoch: - torch.save(model.state_dict(), os.path.join(save_dir, "ep%03d-loss%.3f-val_loss%.3f.pth" % (epoch + 1, loss / epoch_step, val_loss / epoch_step_val))) - # 每次保存最后一个权重 - torch.save(model.state_dict(), os.path.join(save_dir, "last.pth" )) \ No newline at end of file diff --git a/spaces/Kreaols/ChuanhuChatGPT/ChuanhuChatbot.py b/spaces/Kreaols/ChuanhuChatGPT/ChuanhuChatbot.py deleted file mode 100644 index 890e5c7ec70f26a0452ded3e33cd56f488819932..0000000000000000000000000000000000000000 --- a/spaces/Kreaols/ChuanhuChatGPT/ChuanhuChatbot.py +++ /dev/null @@ -1,473 +0,0 @@ -# -*- coding:utf-8 -*- -import os -import logging -import sys - -import gradio as gr - -from modules import config -from modules.config import * -from modules.utils import * -from modules.presets import * -from modules.overwrites import * -from modules.models.models import get_model - -logging.getLogger("httpx").setLevel(logging.WARNING) - -gr.Chatbot._postprocess_chat_messages = postprocess_chat_messages -gr.Chatbot.postprocess = postprocess - -with open("assets/custom.css", "r", encoding="utf-8") as f: - customCSS = f.read() - -def create_new_model(): - return get_model(model_name = MODELS[DEFAULT_MODEL], access_key = my_api_key)[0] - -with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo: - user_name = gr.State("") - promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2)) - user_question = gr.State("") - assert type(my_api_key)==str - user_api_key = gr.State(my_api_key) - current_model = gr.State(create_new_model) - - topic = gr.State(i18n("未命名对话历史记录")) - - with gr.Row(): - gr.HTML(CHUANHU_TITLE, elem_id="app_title") - status_display = gr.Markdown(get_geoip(), elem_id="status_display") - with gr.Row(elem_id="float_display"): - user_info = gr.Markdown(value="getting user info...", elem_id="user_info") - - with gr.Row().style(equal_height=True): - with gr.Column(scale=5): - with gr.Row(): - chatbot = gr.Chatbot(label="Chuanhu Chat", elem_id="chuanhu_chatbot").style(height="100%") - with gr.Row(): - with gr.Column(min_width=225, scale=12): - user_input = gr.Textbox( - elem_id="user_input_tb", - show_label=False, placeholder=i18n("在这里输入") - ).style(container=False) - with gr.Column(min_width=42, scale=1): - submitBtn = gr.Button(value="", variant="primary", elem_id="submit_btn") - cancelBtn = gr.Button(value="", variant="secondary", visible=False, elem_id="cancel_btn") - with gr.Row(): - emptyBtn = gr.Button( - i18n("🧹 新的对话"), elem_id="empty_btn" - ) - retryBtn = gr.Button(i18n("🔄 重新生成")) - delFirstBtn = gr.Button(i18n("🗑️ 删除最旧对话")) - delLastBtn = gr.Button(i18n("🗑️ 删除最新对话")) - with gr.Row(visible=False) as like_dislike_area: - with gr.Column(min_width=20, scale=1): - likeBtn = gr.Button(i18n("👍")) - with gr.Column(min_width=20, scale=1): - dislikeBtn = gr.Button(i18n("👎")) - - with gr.Column(): - with gr.Column(min_width=50, scale=1): - with gr.Tab(label=i18n("模型")): - keyTxt = gr.Textbox( - show_label=True, - placeholder=f"Your API-key...", - value=hide_middle_chars(user_api_key.value), - type="password", - visible=not HIDE_MY_KEY, - label="API-Key", - ) - if multi_api_key: - usageTxt = gr.Markdown(i18n("多账号模式已开启,无需输入key,可直接开始对话"), elem_id="usage_display", elem_classes="insert_block") - else: - usageTxt = gr.Markdown(i18n("**发送消息** 或 **提交key** 以显示额度"), elem_id="usage_display", elem_classes="insert_block") - model_select_dropdown = gr.Dropdown( - label=i18n("选择模型"), choices=MODELS, multiselect=False, value=MODELS[DEFAULT_MODEL], interactive=True - ) - lora_select_dropdown = gr.Dropdown( - label=i18n("选择LoRA模型"), choices=[], multiselect=False, interactive=True, visible=False - ) - with gr.Row(): - single_turn_checkbox = gr.Checkbox(label=i18n("单轮对话"), value=False) - use_websearch_checkbox = gr.Checkbox(label=i18n("使用在线搜索"), value=False) - language_select_dropdown = gr.Dropdown( - label=i18n("选择回复语言(针对搜索&索引功能)"), - choices=REPLY_LANGUAGES, - multiselect=False, - value=REPLY_LANGUAGES[0], - ) - index_files = gr.Files(label=i18n("上传"), type="file") - two_column = gr.Checkbox(label=i18n("双栏pdf"), value=advance_docs["pdf"].get("two_column", False)) - summarize_btn = gr.Button(i18n("总结")) - # TODO: 公式ocr - # formula_ocr = gr.Checkbox(label=i18n("识别公式"), value=advance_docs["pdf"].get("formula_ocr", False)) - - with gr.Tab(label="Prompt"): - systemPromptTxt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入System Prompt..."), - label="System prompt", - value=INITIAL_SYSTEM_PROMPT, - lines=10, - ).style(container=False) - with gr.Accordion(label=i18n("加载Prompt模板"), open=True): - with gr.Column(): - with gr.Row(): - with gr.Column(scale=6): - templateFileSelectDropdown = gr.Dropdown( - label=i18n("选择Prompt模板集合文件"), - choices=get_template_names(plain=True), - multiselect=False, - value=get_template_names(plain=True)[0], - ).style(container=False) - with gr.Column(scale=1): - templateRefreshBtn = gr.Button(i18n("🔄 刷新")) - with gr.Row(): - with gr.Column(): - templateSelectDropdown = gr.Dropdown( - label=i18n("从Prompt模板中加载"), - choices=load_template( - get_template_names(plain=True)[0], mode=1 - ), - multiselect=False, - ).style(container=False) - - with gr.Tab(label=i18n("保存/加载")): - with gr.Accordion(label=i18n("保存/加载对话历史记录"), open=True): - with gr.Column(): - with gr.Row(): - with gr.Column(scale=6): - historyFileSelectDropdown = gr.Dropdown( - label=i18n("从列表中加载对话"), - choices=get_history_names(plain=True), - multiselect=False - ) - with gr.Column(scale=1): - historyRefreshBtn = gr.Button(i18n("🔄 刷新")) - with gr.Row(): - with gr.Column(scale=6): - saveFileName = gr.Textbox( - show_label=True, - placeholder=i18n("设置文件名: 默认为.json,可选为.md"), - label=i18n("设置保存文件名"), - value=i18n("对话历史记录"), - ).style(container=True) - with gr.Column(scale=1): - saveHistoryBtn = gr.Button(i18n("💾 保存对话")) - exportMarkdownBtn = gr.Button(i18n("📝 导出为Markdown")) - gr.Markdown(i18n("默认保存于history文件夹")) - with gr.Row(): - with gr.Column(): - downloadFile = gr.File(interactive=True) - - with gr.Tab(label=i18n("高级")): - gr.Markdown(i18n("# ⚠️ 务必谨慎更改 ⚠️\n\n如果无法使用请恢复默认设置")) - gr.HTML(get_html("appearance_switcher.html").format(label=i18n("切换亮暗色主题")), elem_classes="insert_block") - use_streaming_checkbox = gr.Checkbox( - label=i18n("实时传输回答"), value=True, visible=ENABLE_STREAMING_OPTION - ) - with gr.Accordion(i18n("参数"), open=False): - temperature_slider = gr.Slider( - minimum=-0, - maximum=2.0, - value=1.0, - step=0.1, - interactive=True, - label="temperature", - ) - top_p_slider = gr.Slider( - minimum=-0, - maximum=1.0, - value=1.0, - step=0.05, - interactive=True, - label="top-p", - ) - n_choices_slider = gr.Slider( - minimum=1, - maximum=10, - value=1, - step=1, - interactive=True, - label="n choices", - ) - stop_sequence_txt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入停止符,用英文逗号隔开..."), - label="stop", - value="", - lines=1, - ) - max_context_length_slider = gr.Slider( - minimum=1, - maximum=32768, - value=2000, - step=1, - interactive=True, - label="max context", - ) - max_generation_slider = gr.Slider( - minimum=1, - maximum=32768, - value=1000, - step=1, - interactive=True, - label="max generations", - ) - presence_penalty_slider = gr.Slider( - minimum=-2.0, - maximum=2.0, - value=0.0, - step=0.01, - interactive=True, - label="presence penalty", - ) - frequency_penalty_slider = gr.Slider( - minimum=-2.0, - maximum=2.0, - value=0.0, - step=0.01, - interactive=True, - label="frequency penalty", - ) - logit_bias_txt = gr.Textbox( - show_label=True, - placeholder=f"word:likelihood", - label="logit bias", - value="", - lines=1, - ) - user_identifier_txt = gr.Textbox( - show_label=True, - placeholder=i18n("用于定位滥用行为"), - label=i18n("用户名"), - value=user_name.value, - lines=1, - ) - - with gr.Accordion(i18n("网络设置"), open=False, visible=False): - # 优先展示自定义的api_host - apihostTxt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入API-Host..."), - label="API-Host", - value=config.api_host or shared.API_HOST, - lines=1, - ) - changeAPIURLBtn = gr.Button(i18n("🔄 切换API地址")) - proxyTxt = gr.Textbox( - show_label=True, - placeholder=i18n("在这里输入代理地址..."), - label=i18n("代理地址(示例:http://127.0.0.1:10809)"), - value="", - lines=2, - ) - changeProxyBtn = gr.Button(i18n("🔄 设置代理地址")) - default_btn = gr.Button(i18n("🔙 恢复默认设置")) - - gr.Markdown(CHUANHU_DESCRIPTION, elem_id="description") - gr.HTML(get_html("footer.html").format(versions=versions_html()), elem_id="footer") - - # https://github.com/gradio-app/gradio/pull/3296 - def create_greeting(request: gr.Request): - if hasattr(request, "username") and request.username: # is not None or is not "" - logging.info(f"Get User Name: {request.username}") - user_info, user_name = gr.Markdown.update(value=f"User: {request.username}"), request.username - else: - user_info, user_name = gr.Markdown.update(value=f"", visible=False), "" - current_model = get_model(model_name = MODELS[DEFAULT_MODEL], access_key = my_api_key)[0] - current_model.set_user_identifier(user_name) - chatbot = gr.Chatbot.update(label=MODELS[DEFAULT_MODEL]) - return user_info, user_name, current_model, toggle_like_btn_visibility(DEFAULT_MODEL), *current_model.auto_load(), get_history_names(False, user_name), chatbot - demo.load(create_greeting, inputs=None, outputs=[user_info, user_name, current_model, like_dislike_area, systemPromptTxt, chatbot, historyFileSelectDropdown, chatbot], api_name="load") - chatgpt_predict_args = dict( - fn=predict, - inputs=[ - current_model, - user_question, - chatbot, - use_streaming_checkbox, - use_websearch_checkbox, - index_files, - language_select_dropdown, - ], - outputs=[chatbot, status_display], - show_progress=True, - ) - - start_outputing_args = dict( - fn=start_outputing, - inputs=[], - outputs=[submitBtn, cancelBtn], - show_progress=True, - ) - - end_outputing_args = dict( - fn=end_outputing, inputs=[], outputs=[submitBtn, cancelBtn] - ) - - reset_textbox_args = dict( - fn=reset_textbox, inputs=[], outputs=[user_input] - ) - - transfer_input_args = dict( - fn=transfer_input, inputs=[user_input], outputs=[user_question, user_input, submitBtn, cancelBtn], show_progress=True - ) - - get_usage_args = dict( - fn=billing_info, inputs=[current_model], outputs=[usageTxt], show_progress=False - ) - - load_history_from_file_args = dict( - fn=load_chat_history, - inputs=[current_model, historyFileSelectDropdown, user_name], - outputs=[saveFileName, systemPromptTxt, chatbot] - ) - - - # Chatbot - cancelBtn.click(interrupt, [current_model], []) - - user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args) - user_input.submit(**get_usage_args) - - submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args, api_name="predict").then(**end_outputing_args) - submitBtn.click(**get_usage_args) - - index_files.change(handle_file_upload, [current_model, index_files, chatbot, language_select_dropdown], [index_files, chatbot, status_display]) - summarize_btn.click(handle_summarize_index, [current_model, index_files, chatbot, language_select_dropdown], [chatbot, status_display]) - - emptyBtn.click( - reset, - inputs=[current_model], - outputs=[chatbot, status_display], - show_progress=True, - ) - - retryBtn.click(**start_outputing_args).then( - retry, - [ - current_model, - chatbot, - use_streaming_checkbox, - use_websearch_checkbox, - index_files, - language_select_dropdown, - ], - [chatbot, status_display], - show_progress=True, - ).then(**end_outputing_args) - retryBtn.click(**get_usage_args) - - delFirstBtn.click( - delete_first_conversation, - [current_model], - [status_display], - ) - - delLastBtn.click( - delete_last_conversation, - [current_model, chatbot], - [chatbot, status_display], - show_progress=False - ) - - likeBtn.click( - like, - [current_model], - [status_display], - show_progress=False - ) - - dislikeBtn.click( - dislike, - [current_model], - [status_display], - show_progress=False - ) - - two_column.change(update_doc_config, [two_column], None) - - # LLM Models - keyTxt.change(set_key, [current_model, keyTxt], [user_api_key, status_display], api_name="set_key").then(**get_usage_args) - keyTxt.submit(**get_usage_args) - single_turn_checkbox.change(set_single_turn, [current_model, single_turn_checkbox], None) - model_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt, user_name], [current_model, status_display, chatbot, lora_select_dropdown], show_progress=True, api_name="get_model") - model_select_dropdown.change(toggle_like_btn_visibility, [model_select_dropdown], [like_dislike_area], show_progress=False) - lora_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt, user_name], [current_model, status_display, chatbot], show_progress=True) - - # Template - systemPromptTxt.change(set_system_prompt, [current_model, systemPromptTxt], None) - templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown]) - templateFileSelectDropdown.change( - load_template, - [templateFileSelectDropdown], - [promptTemplates, templateSelectDropdown], - show_progress=True, - ) - templateSelectDropdown.change( - get_template_content, - [promptTemplates, templateSelectDropdown, systemPromptTxt], - [systemPromptTxt], - show_progress=True, - ) - - # S&L - saveHistoryBtn.click( - save_chat_history, - [current_model, saveFileName, chatbot, user_name], - downloadFile, - show_progress=True, - ) - saveHistoryBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown]) - exportMarkdownBtn.click( - export_markdown, - [current_model, saveFileName, chatbot, user_name], - downloadFile, - show_progress=True, - ) - historyRefreshBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown]) - historyFileSelectDropdown.change(**load_history_from_file_args) - downloadFile.change(upload_chat_history, [current_model, downloadFile, user_name], [saveFileName, systemPromptTxt, chatbot]) - - # Advanced - max_context_length_slider.change(set_token_upper_limit, [current_model, max_context_length_slider], None) - temperature_slider.change(set_temperature, [current_model, temperature_slider], None) - top_p_slider.change(set_top_p, [current_model, top_p_slider], None) - n_choices_slider.change(set_n_choices, [current_model, n_choices_slider], None) - stop_sequence_txt.change(set_stop_sequence, [current_model, stop_sequence_txt], None) - max_generation_slider.change(set_max_tokens, [current_model, max_generation_slider], None) - presence_penalty_slider.change(set_presence_penalty, [current_model, presence_penalty_slider], None) - frequency_penalty_slider.change(set_frequency_penalty, [current_model, frequency_penalty_slider], None) - logit_bias_txt.change(set_logit_bias, [current_model, logit_bias_txt], None) - user_identifier_txt.change(set_user_identifier, [current_model, user_identifier_txt], None) - - default_btn.click( - reset_default, [], [apihostTxt, proxyTxt, status_display], show_progress=True - ) - changeAPIURLBtn.click( - change_api_host, - [apihostTxt], - [status_display], - show_progress=True, - ) - changeProxyBtn.click( - change_proxy, - [proxyTxt], - [status_display], - show_progress=True, - ) - -logging.info( - colorama.Back.GREEN - + "\n川虎的温馨提示:访问 http://localhost:7860 查看界面" - + colorama.Style.RESET_ALL -) -# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接 -demo.title = i18n("川虎Chat 🚀") - -if __name__ == "__main__": - reload_javascript() - demo.queue(concurrency_count=CONCURRENT_COUNT).launch( - blocked_paths=["config.json"], - favicon_path="./assets/favicon.ico" - ) diff --git a/spaces/KyanChen/BuildingExtraction/Utils/Augmentations.py b/spaces/KyanChen/BuildingExtraction/Utils/Augmentations.py deleted file mode 100644 index 6664b9450045318a9125e22cdcbcae5bfd24b14a..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/BuildingExtraction/Utils/Augmentations.py +++ /dev/null @@ -1,606 +0,0 @@ -import numpy as np -import cv2 -import torch - -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, data): - for t in self.transforms: - data = t(data) - return data - - def __repr__(self): - format_string = self.__class__.__name__ + '(' - for t in self.transforms: - format_string += '\n' - format_string += ' {0}'.format(t) - format_string += '\n)' - return format_string - - -class ConvertUcharToFloat(object): - """ - Convert img form uchar to float32 - """ - - def __call__(self, data): - data = [x.astype(np.float32) for x in data] - return data - - -class RandomContrast(object): - """ - Get random contrast img - """ - def __init__(self, phase, lower=0.8, upper=1.2, prob=0.5): - self.phase = phase - self.lower = lower - self.upper = upper - self.prob = prob - assert self.upper >= self.lower, "contrast upper must be >= lower!" - assert self.lower > 0, "contrast lower must be non-negative!" - - def __call__(self, data): - if self.phase in ['od', 'seg']: - img, _ = data - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(self.lower, self.upper) - img *= alpha.numpy() - return_data = img, _ - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(self.lower, self.upper) - img1 *= alpha.numpy() - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(self.lower, self.upper) - img2 *= alpha.numpy() - return_data = img1, label1, img2, label2 - return return_data - - -class RandomBrightness(object): - """ - Get random brightness img - """ - def __init__(self, phase, delta=10, prob=0.5): - self.phase = phase - self.delta = delta - self.prob = prob - assert 0. <= self.delta < 255., "brightness delta must between 0 to 255" - - def __call__(self, data): - if self.phase in ['od', 'seg']: - img, _ = data - if torch.rand(1) < self.prob: - delta = torch.FloatTensor(1).uniform_(- self.delta, self.delta) - img += delta.numpy() - return_data = img, _ - - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - delta = torch.FloatTensor(1).uniform_(- self.delta, self.delta) - img1 += delta.numpy() - if torch.rand(1) < self.prob: - delta = torch.FloatTensor(1).uniform_(- self.delta, self.delta) - img2 += delta.numpy() - return_data = img1, label1, img2, label2 - - return return_data - - -class ConvertColor(object): - """ - Convert img color BGR to HSV or HSV to BGR for later img distortion. - """ - def __init__(self, phase, current='RGB', target='HSV'): - self.phase = phase - self.current = current - self.target = target - - def __call__(self, data): - - if self.phase in ['od', 'seg']: - img, _ = data - if self.current == 'RGB' and self.target == 'HSV': - img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) - elif self.current == 'HSV' and self.target == 'RGB': - img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB) - else: - raise NotImplementedError("Convert color fail!") - return_data = img, _ - - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if self.current == 'RGB' and self.target == 'HSV': - img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2HSV) - img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2HSV) - elif self.current == 'HSV' and self.target == 'RGB': - img1 = cv2.cvtColor(img1, cv2.COLOR_HSV2RGB) - img2 = cv2.cvtColor(img2, cv2.COLOR_HSV2RGB) - else: - raise NotImplementedError("Convert color fail!") - return_data = img1, label1, img2, label2 - - return return_data - - -class RandomSaturation(object): - """ - get random saturation img - apply the restriction on saturation S - """ - def __init__(self, phase, lower=0.8, upper=1.2, prob=0.5): - self.phase = phase - self.lower = lower - self.upper = upper - self.prob = prob - assert self.upper >= self.lower, "saturation upper must be >= lower!" - assert self.lower > 0, "saturation lower must be non-negative!" - - def __call__(self, data): - if self.phase in ['od', 'seg']: - img, _ = data - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(self.lower, self.upper) - img[:, :, 1] *= alpha.numpy() - return_data = img, _ - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(self.lower, self.upper) - img1[:, :, 1] *= alpha.numpy() - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(self.lower, self.upper) - img2[:, :, 1] *= alpha.numpy() - return_data = img1, label1, img2, label2 - return return_data - - -class RandomHue(object): - """ - get random Hue img - apply the restriction on Hue H - """ - def __init__(self, phase, delta=10., prob=0.5): - self.phase = phase - self.delta = delta - self.prob = prob - assert 0 <= self.delta < 360, "Hue delta must between 0 to 360!" - - def __call__(self, data): - if self.phase in ['od', 'seg']: - img, _ = data - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(-self.delta, self.delta) - img[:, :, 0] += alpha.numpy() - img[:, :, 0][img[:, :, 0] > 360.0] -= 360.0 - img[:, :, 0][img[:, :, 0] < 0.0] += 360.0 - return_data = img, _ - - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(-self.delta, self.delta) - img1[:, :, 0] += alpha.numpy() - img1[:, :, 0][img1[:, :, 0] > 360.0] -= 360.0 - img1[:, :, 0][img1[:, :, 0] < 0.0] += 360.0 - if torch.rand(1) < self.prob: - alpha = torch.FloatTensor(1).uniform_(-self.delta, self.delta) - img2[:, :, 0] += alpha.numpy() - img2[:, :, 0][img2[:, :, 0] > 360.0] -= 360.0 - img2[:, :, 0][img2[:, :, 0] < 0.0] += 360.0 - - return_data = img1, label1, img2, label2 - - return return_data - - -class RandomChannelNoise(object): - """ - Get random shuffle channels - """ - def __init__(self, phase, prob=0.4): - self.phase = phase - self.prob = prob - self.perms = ((0, 1, 2), (0, 2, 1), - (1, 0, 2), (1, 2, 0), - (2, 0, 1), (2, 1, 0)) - - def __call__(self, data): - if self.phase in ['od', 'seg']: - img, _ = data - if torch.rand(1) < self.prob: - shuffle_factor = self.perms[torch.randint(0, len(self.perms), size=[])] - img = img[:, :, shuffle_factor] - return_data = img, _ - - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - shuffle_factor = self.perms[torch.randint(0, len(self.perms), size=[])] - img1 = img1[:, :, shuffle_factor] - if torch.rand(1) < self.prob: - shuffle_factor = self.perms[torch.randint(0, len(self.perms), size=[])] - img2 = img2[:, :, shuffle_factor] - return_data = img1, label1, img2, label2 - - return return_data - - -class ImgDistortion(object): - """ - Change img by distortion - """ - def __init__(self, phase, prob=0.5): - self.phase = phase - self.prob = prob - self.operation = [ - RandomContrast(phase), - ConvertColor(phase, current='RGB', target='HSV'), - RandomSaturation(phase), - RandomHue(phase), - ConvertColor(phase, current='HSV', target='RGB'), - RandomContrast(phase) - ] - self.random_brightness = RandomBrightness(phase) - self.random_light_noise = RandomChannelNoise(phase) - - def __call__(self, data): - if torch.rand(1) < self.prob: - data = self.random_brightness(data) - if torch.rand(1) < self.prob: - distort = Compose(self.operation[:-1]) - else: - distort = Compose(self.operation[1:]) - data = distort(data) - data = self.random_light_noise(data) - return data - - -class ExpandImg(object): - """ - Get expand img - """ - def __init__(self, phase, prior_mean, prob=0.5, expand_ratio=0.2): - self.phase = phase - self.prior_mean = np.array(prior_mean) * 255 - self.prob = prob - self.expand_ratio = expand_ratio - - def __call__(self, data): - if self.phase == 'seg': - img, label = data - if torch.rand(1) < self.prob: - return data - height, width, channels = img.shape - ratio_width = self.expand_ratio * torch.rand([]) - ratio_height = self.expand_ratio * torch.rand([]) - left, right = torch.randint(high=int(max(1, width * ratio_width)), size=[2]) - top, bottom = torch.randint(high=int(max(1, width * ratio_height)), size=[2]) - img = cv2.copyMakeBorder( - img, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=self.prior_mean) - label = cv2.copyMakeBorder( - label, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=0) - return img, label - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - return data - height, width, channels = img1.shape - ratio_width = self.expand_ratio * torch.rand([]) - ratio_height = self.expand_ratio * torch.rand([]) - left, right = torch.randint(high=int(max(1, width * ratio_width)), size=[2]) - top, bottom = torch.randint(high=int(max(1, width * ratio_height)), size=[2]) - img1 = cv2.copyMakeBorder( - img1, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=self.prior_mean) - label1 = cv2.copyMakeBorder( - label1, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=0) - img2 = cv2.copyMakeBorder( - img2, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=self.prior_mean) - label2 = cv2.copyMakeBorder( - label2, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=0) - return img1, label1, img2, label2 - - elif self.phase == 'od': - if torch.rand(1) < self.prob: - return data - img, label = data - height, width, channels = img.shape - ratio_width = self.expand_ratio * torch.rand([]) - ratio_height = self.expand_ratio * torch.rand([]) - left, right = torch.randint(high=int(max(1, width * ratio_width)), size=[2]) - top, bottom = torch.randint(high=int(max(1, width * ratio_height)), size=[2]) - left = int(left) - right = int(right) - top = int(top) - bottom = int(bottom) - img = cv2.copyMakeBorder( - img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=self.prior_mean) - - label[:, 1::2] += left - label[:, 2::2] += top - return img, label - - -class RandomSampleCrop(object): - """ - Crop - Arguments: - img (Image): the image being input during training - boxes (Tensor): the original bounding boxes in pt form - label (Tensor): the class label for each bbox - mode (float tuple): the min and max jaccard overlaps - Return: - (img, boxes, classes) - img (Image): the cropped image - boxes (Tensor): the adjusted bounding boxes in pt form - label (Tensor): the class label for each bbox - """ - def __init__(self, - phase, - original_size=[512, 512], - prob=0.5, - crop_scale_ratios_range=[0.8, 1.2], - aspect_ratio_range=[4./5, 5./4]): - self.phase = phase - self.prob = prob - self.scale_range = crop_scale_ratios_range - self.original_size = original_size - self.aspect_ratio_range = aspect_ratio_range # h/w - self.max_try_times = 500 - - def __call__(self, data): - if self.phase == 'seg': - img, label = data - w, h, c = img.shape - if torch.rand(1) < self.prob: - return data - else: - try_times = 0 - while try_times < self.max_try_times: - crop_w = torch.randint( - min(w, int(self.scale_range[0] * self.original_size[0])), - min(w + 1, int(self.scale_range[1] * self.original_size[0])), - size=[] - ) - crop_h = torch.randint( - min(h, int(self.scale_range[0] * self.original_size[1])), - min(h + 1, int(self.scale_range[1] * self.original_size[1])), - size=[] - ) - # aspect ratio constraint - if self.aspect_ratio_range[0] < crop_h / crop_w < self.aspect_ratio_range[1]: - break - else: - try_times += 1 - if try_times >= self.max_try_times: - print("try times over max threshold!", flush=True) - return img, label - - left = torch.randint(0, w - crop_w + 1, size=[]) - top = torch.randint(0, h - crop_h + 1, size=[]) - img = img[top:(top + crop_h), left:(left + crop_w), :] - label = label[top:(top + crop_h), left:(left + crop_w)] - return img, label - - elif self.phase == 'od': - if torch.rand(1) < self.prob: - return data - img, label = data - w, h, c = img.shape - - while True: - crop_w = torch.randint( - min(w, int(self.scale_range[0] * self.original_size[0])), - min(w + 1, int(self.scale_range[1] * self.original_size[0])), - size=[] - ) - crop_h = torch.randint( - min(h, int(self.scale_range[0] * self.original_size[1])), - min(h + 1, int(self.scale_range[1] * self.original_size[1])), - size=[] - ) - - # aspect ratio constraint - if self.aspect_ratio_range[0] < crop_h / crop_w < self.aspect_ratio_range[1]: - break - - left = torch.randint(0, w - crop_w + 1, size=[]) - top = torch.randint(0, h - crop_h + 1, size=[]) - left = left.numpy() - top = top.numpy() - crop_h = crop_h.numpy() - crop_w = crop_w.numpy() - img = img[top:(top + crop_h), left:(left + crop_w), :] - if len(label): - # keep overlap with gt box IF center in sampled patch - centers = (label[:, 1:3] + label[:, 3:]) / 2.0 - # mask in all gt boxes that above and to the left of centers - m1 = (left <= centers[:, 0]) * (top <= centers[:, 1]) - # mask in all gt boxes that under and to the right of centers - m2 = ((left + crop_w) >= centers[:, 0]) * ((top + crop_h) > centers[:, 1]) - # mask in that both m1 and m2 are true - mask = m1 * m2 - - # take only matching gt boxes - current_label = label[mask, :] - - # adjust to crop (by substracting crop's left,top) - current_label[:, 1::2] -= left - current_label[:, 2::2] -= top - label = current_label - return img, label - - -class RandomMirror(object): - def __init__(self, phase, prob=0.5): - self.phase = phase - self.prob = prob - - def __call__(self, data): - if self.phase == 'seg': - img, label = data - if torch.rand(1) < self.prob: - img = img[:, ::-1] - label = label[:, ::-1] - return img, label - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - img1 = img1[:, ::-1] - label1 = label1[:, ::-1] - img2 = img2[:, ::-1] - label2 = label2[:, ::-1] - return img1, label1, img2, label2 - elif self.phase == 'od': - img, label = data - if torch.rand(1) < self.prob: - _, width, _ = img.shape - img = img[:, ::-1] - label[:, 1::2] = width - label[:, 3::-2] - return img, label - - -class RandomFlipV(object): - def __init__(self, phase, prob=0.5): - self.phase = phase - self.prob = prob - - def __call__(self, data): - if self.phase == 'seg': - img, label = data - if torch.rand(1) < self.prob: - img = img[::-1, :] - label = label[::-1, :] - return img, label - elif self.phase == 'cd': - img1, label1, img2, label2 = data - if torch.rand(1) < self.prob: - img1 = img1[::-1, :] - label1 = label1[::-1, :] - img2 = img2[::-1, :] - label2 = label2[::-1, :] - return img1, label1, img2, label2 - elif self.phase == 'od': - img, label = data - if torch.rand(1) < self.prob: - height, _, _ = img.shape - img = img[::-1, :] - label[:, 2::2] = height - label[:, 4:1:-2] - return img, label - - -class Resize(object): - def __init__(self, phase, size): - self.phase = phase - self.size = size - - def __call__(self, data): - if self.phase == 'seg': - img, label = data - img = cv2.resize(img, self.size, interpolation=cv2.INTER_LINEAR) - # for label - label = cv2.resize(label, self.size, interpolation=cv2.INTER_NEAREST) - return img, label - elif self.phase == 'cd': - img1, label1, img2, label2 = data - img1 = cv2.resize(img1, self.size, interpolation=cv2.INTER_LINEAR) - img2 = cv2.resize(img2, self.size, interpolation=cv2.INTER_LINEAR) - # for label - label1 = cv2.resize(label1, self.size, interpolation=cv2.INTER_NEAREST) - label2 = cv2.resize(label2, self.size, interpolation=cv2.INTER_NEAREST) - return img1, label1, img2, label2 - elif self.phase == 'od': - img, label = data - height, width, _ = img.shape - img = cv2.resize(img, self.size, interpolation=cv2.INTER_LINEAR) - label[:, 1::2] = label[:, 1::2] / width * self.size[0] - label[:, 2::2] = label[:, 2::2] / height * self.size[1] - return img, label - - -class Normalize(object): - def __init__(self, phase, prior_mean, prior_std): - self.phase = phase - self.prior_mean = np.array([[prior_mean]], dtype=np.float32) - self.prior_std = np.array([[prior_std]], dtype=np.float32) - - def __call__(self, data): - if self.phase in ['od', 'seg']: - img, _ = data - img = img / 255. - img = (img - self.prior_mean) / (self.prior_std + 1e-10) - - return img, _ - elif self.phase == 'cd': - img1, label1, img2, label2 = data - img1 = img1 / 255. - img1 = (img1 - self.prior_mean) / (self.prior_std + 1e-10) - img2 = img2 / 255. - img2 = (img2 - self.prior_mean) / (self.prior_std + 1e-10) - - return img1, label1, img2, label2 - - -class InvNormalize(object): - def __init__(self, prior_mean, prior_std): - self.prior_mean = np.array([[prior_mean]], dtype=np.float32) - self.prior_std = np.array([[prior_std]], dtype=np.float32) - - def __call__(self, img): - img = img * self.prior_std + self.prior_mean - img = img * 255. - img = np.clip(img, a_min=0, a_max=255) - return img - - -class Augmentations(object): - def __init__(self, size, prior_mean=0, prior_std=1, pattern='train', phase='seg', *args, **kwargs): - self.size = size - self.prior_mean = prior_mean - self.prior_std = prior_std - self.phase = phase - - augments = { - 'train': Compose([ - ConvertUcharToFloat(), - ImgDistortion(self.phase), - ExpandImg(self.phase, self.prior_mean), - RandomSampleCrop(self.phase, original_size=self.size), - RandomMirror(self.phase), - RandomFlipV(self.phase), - Resize(self.phase, self.size), - Normalize(self.phase, self.prior_mean, self.prior_std), - ]), - 'val': Compose([ - ConvertUcharToFloat(), - Resize(self.phase, self.size), - Normalize(self.phase, self.prior_mean, self.prior_std), - ]), - 'test': Compose([ - ConvertUcharToFloat(), - Resize(self.phase, self.size), - Normalize(self.phase, self.prior_mean, self.prior_std), - ]) - } - self.augment = augments[pattern] - - def __call__(self, data): - return self.augment(data) - diff --git a/spaces/KyanChen/RSPrompter/mmdet/structures/mask/mask_target.py b/spaces/KyanChen/RSPrompter/mmdet/structures/mask/mask_target.py deleted file mode 100644 index b2fc5f1878300446b114c9f57c6a885fea8c927c..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/structures/mask/mask_target.py +++ /dev/null @@ -1,127 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import numpy as np -import torch -from torch.nn.modules.utils import _pair - - -def mask_target(pos_proposals_list, pos_assigned_gt_inds_list, gt_masks_list, - cfg): - """Compute mask target for positive proposals in multiple images. - - Args: - pos_proposals_list (list[Tensor]): Positive proposals in multiple - images, each has shape (num_pos, 4). - pos_assigned_gt_inds_list (list[Tensor]): Assigned GT indices for each - positive proposals, each has shape (num_pos,). - gt_masks_list (list[:obj:`BaseInstanceMasks`]): Ground truth masks of - each image. - cfg (dict): Config dict that specifies the mask size. - - Returns: - Tensor: Mask target of each image, has shape (num_pos, w, h). - - Example: - >>> from mmengine.config import Config - >>> import mmdet - >>> from mmdet.data_elements.mask import BitmapMasks - >>> from mmdet.data_elements.mask.mask_target import * - >>> H, W = 17, 18 - >>> cfg = Config({'mask_size': (13, 14)}) - >>> rng = np.random.RandomState(0) - >>> # Positive proposals (tl_x, tl_y, br_x, br_y) for each image - >>> pos_proposals_list = [ - >>> torch.Tensor([ - >>> [ 7.2425, 5.5929, 13.9414, 14.9541], - >>> [ 7.3241, 3.6170, 16.3850, 15.3102], - >>> ]), - >>> torch.Tensor([ - >>> [ 4.8448, 6.4010, 7.0314, 9.7681], - >>> [ 5.9790, 2.6989, 7.4416, 4.8580], - >>> [ 0.0000, 0.0000, 0.1398, 9.8232], - >>> ]), - >>> ] - >>> # Corresponding class index for each proposal for each image - >>> pos_assigned_gt_inds_list = [ - >>> torch.LongTensor([7, 0]), - >>> torch.LongTensor([5, 4, 1]), - >>> ] - >>> # Ground truth mask for each true object for each image - >>> gt_masks_list = [ - >>> BitmapMasks(rng.rand(8, H, W), height=H, width=W), - >>> BitmapMasks(rng.rand(6, H, W), height=H, width=W), - >>> ] - >>> mask_targets = mask_target( - >>> pos_proposals_list, pos_assigned_gt_inds_list, - >>> gt_masks_list, cfg) - >>> assert mask_targets.shape == (5,) + cfg['mask_size'] - """ - cfg_list = [cfg for _ in range(len(pos_proposals_list))] - mask_targets = map(mask_target_single, pos_proposals_list, - pos_assigned_gt_inds_list, gt_masks_list, cfg_list) - mask_targets = list(mask_targets) - if len(mask_targets) > 0: - mask_targets = torch.cat(mask_targets) - return mask_targets - - -def mask_target_single(pos_proposals, pos_assigned_gt_inds, gt_masks, cfg): - """Compute mask target for each positive proposal in the image. - - Args: - pos_proposals (Tensor): Positive proposals. - pos_assigned_gt_inds (Tensor): Assigned GT inds of positive proposals. - gt_masks (:obj:`BaseInstanceMasks`): GT masks in the format of Bitmap - or Polygon. - cfg (dict): Config dict that indicate the mask size. - - Returns: - Tensor: Mask target of each positive proposals in the image. - - Example: - >>> from mmengine.config import Config - >>> import mmdet - >>> from mmdet.data_elements.mask import BitmapMasks - >>> from mmdet.data_elements.mask.mask_target import * # NOQA - >>> H, W = 32, 32 - >>> cfg = Config({'mask_size': (7, 11)}) - >>> rng = np.random.RandomState(0) - >>> # Masks for each ground truth box (relative to the image) - >>> gt_masks_data = rng.rand(3, H, W) - >>> gt_masks = BitmapMasks(gt_masks_data, height=H, width=W) - >>> # Predicted positive boxes in one image - >>> pos_proposals = torch.FloatTensor([ - >>> [ 16.2, 5.5, 19.9, 20.9], - >>> [ 17.3, 13.6, 19.3, 19.3], - >>> [ 14.8, 16.4, 17.0, 23.7], - >>> [ 0.0, 0.0, 16.0, 16.0], - >>> [ 4.0, 0.0, 20.0, 16.0], - >>> ]) - >>> # For each predicted proposal, its assignment to a gt mask - >>> pos_assigned_gt_inds = torch.LongTensor([0, 1, 2, 1, 1]) - >>> mask_targets = mask_target_single( - >>> pos_proposals, pos_assigned_gt_inds, gt_masks, cfg) - >>> assert mask_targets.shape == (5,) + cfg['mask_size'] - """ - device = pos_proposals.device - mask_size = _pair(cfg.mask_size) - binarize = not cfg.get('soft_mask_target', False) - num_pos = pos_proposals.size(0) - if num_pos > 0: - proposals_np = pos_proposals.cpu().numpy() - maxh, maxw = gt_masks.height, gt_masks.width - proposals_np[:, [0, 2]] = np.clip(proposals_np[:, [0, 2]], 0, maxw) - proposals_np[:, [1, 3]] = np.clip(proposals_np[:, [1, 3]], 0, maxh) - pos_assigned_gt_inds = pos_assigned_gt_inds.cpu().numpy() - - mask_targets = gt_masks.crop_and_resize( - proposals_np, - mask_size, - device=device, - inds=pos_assigned_gt_inds, - binarize=binarize).to_ndarray() - - mask_targets = torch.from_numpy(mask_targets).float().to(device) - else: - mask_targets = pos_proposals.new_zeros((0, ) + mask_size) - - return mask_targets diff --git a/spaces/LDJA/iris/README.md b/spaces/LDJA/iris/README.md deleted file mode 100644 index d9ac2610f04d6704c270af38a3b5ab8e7dbe86f6..0000000000000000000000000000000000000000 --- a/spaces/LDJA/iris/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Iris -emoji: 🔥 -colorFrom: pink -colorTo: red -sdk: docker -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/LZRi/LZR-Bert-VITS2/short_audio_transcribe.py b/spaces/LZRi/LZR-Bert-VITS2/short_audio_transcribe.py deleted file mode 100644 index f1e8b30671f2c2f2fa3c93feb1f4edd3fbe2f545..0000000000000000000000000000000000000000 --- a/spaces/LZRi/LZR-Bert-VITS2/short_audio_transcribe.py +++ /dev/null @@ -1,122 +0,0 @@ -import whisper -import os -import json -import torchaudio -import argparse -import torch - -lang2token = { - 'zh': "[ZH]", - 'ja': "[JA]", - "en": "[EN]", - } -def transcribe_one(audio_path): - # load audio and pad/trim it to fit 30 seconds - audio = whisper.load_audio(audio_path) - audio = whisper.pad_or_trim(audio) - - # make log-Mel spectrogram and move to the same device as the model - mel = whisper.log_mel_spectrogram(audio).to(model.device) - - # detect the spoken language - _, probs = model.detect_language(mel) - print(f"Detected language: {max(probs, key=probs.get)}") - lang = max(probs, key=probs.get) - # decode the audio - options = whisper.DecodingOptions(beam_size=5) - result = whisper.decode(model, mel, options) - - # print the recognized text - print(result.text) - return lang, result.text -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--languages", default="CJE") - parser.add_argument("--whisper_size", default="medium") - args = parser.parse_args() - if args.languages == "CJE": - lang2token = { - 'zh': "[ZH]", - 'ja': "[JA]", - "en": "[EN]", - } - elif args.languages == "CJ": - lang2token = { - 'zh': "[ZH]", - 'ja': "[JA]", - } - elif args.languages == "C": - lang2token = { - 'zh': "[ZH]", - } - assert (torch.cuda.is_available()), "Please enable GPU in order to run Whisper!" - model = whisper.load_model(args.whisper_size) - parent_dir = "./custom_character_voice/" - speaker_names = list(os.walk(parent_dir))[0][1] - speaker_annos = [] - total_files = sum([len(files) for r, d, files in os.walk(parent_dir)]) - # resample audios - # 2023/4/21: Get the target sampling rate - with open("./configs/config.json", 'r', encoding='utf-8') as f: - hps = json.load(f) - target_sr = hps['data']['sampling_rate'] - processed_files = 0 - for speaker in speaker_names: - for i, wavfile in enumerate(list(os.walk(parent_dir + speaker))[0][2]): - # try to load file as audio - if wavfile.startswith("processed_"): - continue - try: - wav, sr = torchaudio.load(parent_dir + speaker + "/" + wavfile, frame_offset=0, num_frames=-1, normalize=True, - channels_first=True) - wav = wav.mean(dim=0).unsqueeze(0) - if sr != target_sr: - wav = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sr)(wav) - if wav.shape[1] / sr > 20: - print(f"{wavfile} too long, ignoring\n") - save_path = parent_dir + speaker + "/" + f"processed_{i}.wav" - torchaudio.save(save_path, wav, target_sr, channels_first=True) - # transcribe text - lang, text = transcribe_one(save_path) - if lang not in list(lang2token.keys()): - print(f"{lang} not supported, ignoring\n") - continue - text = "ZH|" + text + "\n"# - #text = lang2token[lang] + text + lang2token[lang] + "\n" - speaker_annos.append(save_path + "|" + speaker + "|" + text) - - processed_files += 1 - print(f"Processed: {processed_files}/{total_files}") - except: - continue - - # # clean annotation - # import argparse - # import text - # from utils import load_filepaths_and_text - # for i, line in enumerate(speaker_annos): - # path, sid, txt = line.split("|") - # cleaned_text = text._clean_text(txt, ["cjke_cleaners2"]) - # cleaned_text += "\n" if not cleaned_text.endswith("\n") else "" - # speaker_annos[i] = path + "|" + sid + "|" + cleaned_text - # write into annotation - if len(speaker_annos) == 0: - print("Warning: no short audios found, this IS expected if you have only uploaded long audios, videos or video links.") - print("this IS NOT expected if you have uploaded a zip file of short audios. Please check your file structure or make sure your audio language is supported.") - with open("./filelists/short_character_anno.list", 'w', encoding='utf-8') as f: - for line in speaker_annos: - f.write(line) - - # import json - # # generate new config - # with open("./configs/finetune_speaker.json", 'r', encoding='utf-8') as f: - # hps = json.load(f) - # # modify n_speakers - # hps['data']["n_speakers"] = 1000 + len(speaker2id) - # # add speaker names - # for speaker in speaker_names: - # hps['speakers'][speaker] = speaker2id[speaker] - # # save modified config - # with open("./configs/modified_finetune_speaker.json", 'w', encoding='utf-8') as f: - # json.dump(hps, f, indent=2) - # print("finished") diff --git a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_libs/slicer2.py b/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_libs/slicer2.py deleted file mode 100644 index 5b29ee262aa54045e807be2cffeb41687499ba58..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_libs/slicer2.py +++ /dev/null @@ -1,260 +0,0 @@ -import numpy as np - - -# This function is obtained from librosa. -def get_rms( - y, - frame_length=2048, - hop_length=512, - pad_mode="constant", -): - padding = (int(frame_length // 2), int(frame_length // 2)) - y = np.pad(y, padding, mode=pad_mode) - - axis = -1 - # put our new within-frame axis at the end for now - out_strides = y.strides + tuple([y.strides[axis]]) - # Reduce the shape on the framing axis - x_shape_trimmed = list(y.shape) - x_shape_trimmed[axis] -= frame_length - 1 - out_shape = tuple(x_shape_trimmed) + tuple([frame_length]) - xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides) - if axis < 0: - target_axis = axis - 1 - else: - target_axis = axis + 1 - xw = np.moveaxis(xw, -1, target_axis) - # Downsample along the target axis - slices = [slice(None)] * xw.ndim - slices[axis] = slice(0, None, hop_length) - x = xw[tuple(slices)] - - # Calculate power - power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True) - - return np.sqrt(power) - - -class Slicer: - def __init__( - self, - sr: int, - threshold: float = -40.0, - min_length: int = 5000, - min_interval: int = 300, - hop_size: int = 20, - max_sil_kept: int = 5000, - ): - if not min_length >= min_interval >= hop_size: - raise ValueError( - "The following condition must be satisfied: min_length >= min_interval >= hop_size" - ) - if not max_sil_kept >= hop_size: - raise ValueError( - "The following condition must be satisfied: max_sil_kept >= hop_size" - ) - min_interval = sr * min_interval / 1000 - self.threshold = 10 ** (threshold / 20.0) - self.hop_size = round(sr * hop_size / 1000) - self.win_size = min(round(min_interval), 4 * self.hop_size) - self.min_length = round(sr * min_length / 1000 / self.hop_size) - self.min_interval = round(min_interval / self.hop_size) - self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size) - - def _apply_slice(self, waveform, begin, end): - if len(waveform.shape) > 1: - return waveform[ - :, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size) - ] - else: - return waveform[ - begin * self.hop_size : min(waveform.shape[0], end * self.hop_size) - ] - - # @timeit - def slice(self, waveform): - if len(waveform.shape) > 1: - samples = waveform.mean(axis=0) - else: - samples = waveform - if samples.shape[0] <= self.min_length: - return [waveform] - rms_list = get_rms( - y=samples, frame_length=self.win_size, hop_length=self.hop_size - ).squeeze(0) - sil_tags = [] - silence_start = None - clip_start = 0 - for i, rms in enumerate(rms_list): - # Keep looping while frame is silent. - if rms < self.threshold: - # Record start of silent frames. - if silence_start is None: - silence_start = i - continue - # Keep looping while frame is not silent and silence start has not been recorded. - if silence_start is None: - continue - # Clear recorded silence start if interval is not enough or clip is too short - is_leading_silence = silence_start == 0 and i > self.max_sil_kept - need_slice_middle = ( - i - silence_start >= self.min_interval - and i - clip_start >= self.min_length - ) - if not is_leading_silence and not need_slice_middle: - silence_start = None - continue - # Need slicing. Record the range of silent frames to be removed. - if i - silence_start <= self.max_sil_kept: - pos = rms_list[silence_start : i + 1].argmin() + silence_start - if silence_start == 0: - sil_tags.append((0, pos)) - else: - sil_tags.append((pos, pos)) - clip_start = pos - elif i - silence_start <= self.max_sil_kept * 2: - pos = rms_list[ - i - self.max_sil_kept : silence_start + self.max_sil_kept + 1 - ].argmin() - pos += i - self.max_sil_kept - pos_l = ( - rms_list[ - silence_start : silence_start + self.max_sil_kept + 1 - ].argmin() - + silence_start - ) - pos_r = ( - rms_list[i - self.max_sil_kept : i + 1].argmin() - + i - - self.max_sil_kept - ) - if silence_start == 0: - sil_tags.append((0, pos_r)) - clip_start = pos_r - else: - sil_tags.append((min(pos_l, pos), max(pos_r, pos))) - clip_start = max(pos_r, pos) - else: - pos_l = ( - rms_list[ - silence_start : silence_start + self.max_sil_kept + 1 - ].argmin() - + silence_start - ) - pos_r = ( - rms_list[i - self.max_sil_kept : i + 1].argmin() - + i - - self.max_sil_kept - ) - if silence_start == 0: - sil_tags.append((0, pos_r)) - else: - sil_tags.append((pos_l, pos_r)) - clip_start = pos_r - silence_start = None - # Deal with trailing silence. - total_frames = rms_list.shape[0] - if ( - silence_start is not None - and total_frames - silence_start >= self.min_interval - ): - silence_end = min(total_frames, silence_start + self.max_sil_kept) - pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start - sil_tags.append((pos, total_frames + 1)) - # Apply and return slices. - if len(sil_tags) == 0: - return [waveform] - else: - chunks = [] - if sil_tags[0][0] > 0: - chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0])) - for i in range(len(sil_tags) - 1): - chunks.append( - self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]) - ) - if sil_tags[-1][1] < total_frames: - chunks.append( - self._apply_slice(waveform, sil_tags[-1][1], total_frames) - ) - return chunks - - -def main(): - import os.path - from argparse import ArgumentParser - - import librosa - import soundfile - - parser = ArgumentParser() - parser.add_argument("audio", type=str, help="The audio to be sliced") - parser.add_argument( - "--out", type=str, help="Output directory of the sliced audio clips" - ) - parser.add_argument( - "--db_thresh", - type=float, - required=False, - default=-40, - help="The dB threshold for silence detection", - ) - parser.add_argument( - "--min_length", - type=int, - required=False, - default=5000, - help="The minimum milliseconds required for each sliced audio clip", - ) - parser.add_argument( - "--min_interval", - type=int, - required=False, - default=300, - help="The minimum milliseconds for a silence part to be sliced", - ) - parser.add_argument( - "--hop_size", - type=int, - required=False, - default=10, - help="Frame length in milliseconds", - ) - parser.add_argument( - "--max_sil_kept", - type=int, - required=False, - default=500, - help="The maximum silence length kept around the sliced clip, presented in milliseconds", - ) - args = parser.parse_args() - out = args.out - if out is None: - out = os.path.dirname(os.path.abspath(args.audio)) - audio, sr = librosa.load(args.audio, sr=None, mono=False) - slicer = Slicer( - sr=sr, - threshold=args.db_thresh, - min_length=args.min_length, - min_interval=args.min_interval, - hop_size=args.hop_size, - max_sil_kept=args.max_sil_kept, - ) - chunks = slicer.slice(audio) - if not os.path.exists(out): - os.makedirs(out) - for i, chunk in enumerate(chunks): - if len(chunk.shape) > 1: - chunk = chunk.T - soundfile.write( - os.path.join( - out, - f"%s_%d.wav" - % (os.path.basename(args.audio).rsplit(".", maxsplit=1)[0], i), - ), - chunk, - sr, - ) - - -if __name__ == "__main__": - main() diff --git a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/modules/train/extract/extract_f0_print.py b/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/modules/train/extract/extract_f0_print.py deleted file mode 100644 index b2754e0d056f8af560e3beb18b72f6aa8d61499a..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/modules/train/extract/extract_f0_print.py +++ /dev/null @@ -1,301 +0,0 @@ -import os -import sys -import traceback - -import parselmouth - -now_dir = os.getcwd() -sys.path.append(now_dir) -import logging - - -import numpy as np -import pyworld -import torchcrepe -import torch -#from torch import Tensor # Fork Feature. Used for pitch prediction for torch crepe. -import tqdm -from lib.infer.infer_libs.audio import load_audio - -logging.getLogger("numba").setLevel(logging.WARNING) -from multiprocessing import Process - -exp_dir = sys.argv[1] -f = open("%s/extract_f0_feature.log" % exp_dir, "a+") - -DoFormant = False -Quefrency = 1.0 -Timbre = 1.0 - -def printt(strr): - print(strr) - f.write(f"{strr}\n") - f.flush() - - -n_p = int(sys.argv[2]) -f0method = sys.argv[3] -crepe_hop_length = 0 -try: - crepe_hop_length = int(sys.argv[4]) -except: - print("Temp Issue. echl is not being passed with argument!") - crepe_hop_length = 128 - -class FeatureInput(object): - def __init__(self, samplerate=16000, hop_size=160): - self.fs = samplerate - self.hop = hop_size - - self.f0_method_dict = self.get_f0_method_dict() - - self.f0_bin = 256 - self.f0_max = 1100.0 - self.f0_min = 50.0 - self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700) - self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700) - - def mncrepe(self, method, x, p_len, crepe_hop_length): - f0 = None - torch_device_index = 0 - torch_device = torch.device( - f"cuda:{torch_device_index % torch.cuda.device_count()}" - ) if torch.cuda.is_available() \ - else torch.device("mps") if torch.backends.mps.is_available() \ - else torch.device("cpu") - - audio = torch.from_numpy(x.astype(np.float32)).to(torch_device, copy=True) - audio /= torch.quantile(torch.abs(audio), 0.999) - audio = torch.unsqueeze(audio, dim=0) - if audio.ndim == 2 and audio.shape[0] > 1: - audio = torch.mean(audio, dim=0, keepdim=True).detach() - audio = audio.detach() - - if method == 'mangio-crepe': - pitch: torch.Tensor = torchcrepe.predict( - audio, - self.fs, - crepe_hop_length, - self.f0_min, - self.f0_max, - "full", - batch_size=crepe_hop_length * 2, - device=torch_device, - pad=True, - ) - p_len = p_len or x.shape[0] // crepe_hop_length - # Resize the pitch - source = np.array(pitch.squeeze(0).cpu().float().numpy()) - source[source < 0.001] = np.nan - target = np.interp( - np.arange(0, len(source) * p_len, len(source)) / p_len, - np.arange(0, len(source)), - source, - ) - f0 = np.nan_to_num(target) - - elif method == 'crepe': - batch_size = 512 - audio = torch.tensor(np.copy(x))[None].float() - f0, pd = torchcrepe.predict( - audio, - self.fs, - 160, - self.f0_min, - self.f0_max, - "full", - batch_size=batch_size, - device=torch_device, - return_periodicity=True, - ) - pd = torchcrepe.filter.median(pd, 3) - f0 = torchcrepe.filter.mean(f0, 3) - f0[pd < 0.1] = 0 - f0 = f0[0].cpu().numpy() - f0 = f0[1:] # Get rid of extra first frame - - return f0 - - def get_pm(self, x, p_len): - f0 = parselmouth.Sound(x, self.fs).to_pitch_ac( - time_step=160 / 16000, - voicing_threshold=0.6, - pitch_floor=self.f0_min, - pitch_ceiling=self.f0_max, - ).selected_array["frequency"] - - return np.pad( - f0, - [[max(0, (p_len - len(f0) + 1) // 2), max(0, p_len - len(f0) - (p_len - len(f0) + 1) // 2)]], - mode="constant" - ) - - def get_harvest(self, x): - f0_spectral = pyworld.harvest( - x.astype(np.double), - fs=self.fs, - f0_ceil=self.f0_max, - f0_floor=self.f0_min, - frame_period=1000 * self.hop / self.fs, - ) - return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.fs) - - def get_dio(self, x): - f0_spectral = pyworld.dio( - x.astype(np.double), - fs=self.fs, - f0_ceil=self.f0_max, - f0_floor=self.f0_min, - frame_period=1000 * self.hop / self.fs, - ) - return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.fs) - - def get_rmvpe(self, x): - if hasattr(self, "model_rmvpe") == False: - from lib.infer.infer_libs.rmvpe import RMVPE - - print("Loading rmvpe model") - self.model_rmvpe = RMVPE( - "assets/rmvpe/rmvpe.pt", is_half=False, device="cpu" - ) - return self.model_rmvpe.infer_from_audio(x, thred=0.03) - - def get_rmvpe_dml(self, x): - ... - - def get_f0_method_dict(self): - return { - "pm": self.get_pm, - "harvest": self.get_harvest, - "dio": self.get_dio, - "rmvpe": self.get_rmvpe - } - - def get_f0_hybrid_computation( - self, - methods_str, - x, - p_len, - crepe_hop_length, - ): - # Get various f0 methods from input to use in the computation stack - s = methods_str - s = s.split("hybrid")[1] - s = s.replace("[", "").replace("]", "") - methods = s.split("+") - f0_computation_stack = [] - - for method in methods: - if method in self.f0_method_dict: - f0 = self.f0_method_dict[method](x, p_len) if method == 'pm' else self.f0_method_dict[method](x) - f0_computation_stack.append(f0) - elif method == 'crepe' or method == 'mangio-crepe': - self.the_other_complex_function(x, method, crepe_hop_length) - - if len(f0_computation_stack) != 0: - f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0) if len(f0_computation_stack)>1 else f0_computation_stack[0] - return f0_median_hybrid - else: - raise ValueError("No valid methods were provided") - - def compute_f0(self, path, f0_method, crepe_hop_length): - x = load_audio(path, self.fs, DoFormant, Quefrency, Timbre) - p_len = x.shape[0] // self.hop - - if f0_method in self.f0_method_dict: - f0 = self.f0_method_dict[f0_method](x, p_len) if f0_method == 'pm' else self.f0_method_dict[f0_method](x) - elif f0_method in ['crepe', 'mangio-crepe']: - f0 = self.mncrepe(f0_method, x, p_len, crepe_hop_length) - elif "hybrid" in f0_method: # EXPERIMENTAL - # Perform hybrid median pitch estimation - f0 = self.get_f0_hybrid_computation( - f0_method, - x, - p_len, - crepe_hop_length, - ) - return f0 - - def coarse_f0(self, f0): - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - self.f0_mel_min) * ( - self.f0_bin - 2 - ) / (self.f0_mel_max - self.f0_mel_min) + 1 - - # use 0 or 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > self.f0_bin - 1] = self.f0_bin - 1 - f0_coarse = np.rint(f0_mel).astype(int) - assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, ( - f0_coarse.max(), - f0_coarse.min(), - ) - return f0_coarse - - def go(self, paths, f0_method, crepe_hop_length, thread_n): - os.system('cls' if os.name == 'nt' else 'clear') - if len(paths) == 0: - printt("no-f0-todo") - return - with tqdm.tqdm(total=len(paths), leave=True, position=thread_n) as pbar: - description = f"Thread {thread_n} | Hop-Length: {crepe_hop_length}" - pbar.set_description(description) - - for idx, (inp_path, opt_path1, opt_path2) in enumerate(paths): - try: - if ( - os.path.exists(opt_path1 + ".npy") - and os.path.exists(opt_path2 + ".npy") - ): - pbar.update(1) - continue - - featur_pit = self.compute_f0(inp_path, f0_method, crepe_hop_length) - np.save( - opt_path2, - featur_pit, - allow_pickle=False, - ) # nsf - coarse_pit = self.coarse_f0(featur_pit) - np.save( - opt_path1, - coarse_pit, - allow_pickle=False, - ) # ori - pbar.update(1) - except Exception as e: - printt(f"f0fail-{idx}-{inp_path}-{traceback.format_exc()}") - - -if __name__ == "__main__": - # exp_dir=r"E:\codes\py39\dataset\mi-test" - # n_p=16 - # f = open("%s/log_extract_f0.log"%exp_dir, "w") - printt(sys.argv) - featureInput = FeatureInput() - paths = [] - inp_root = "%s/1_16k_wavs" % (exp_dir) - opt_root1 = "%s/2a_f0" % (exp_dir) - opt_root2 = "%s/2b-f0nsf" % (exp_dir) - - os.makedirs(opt_root1, exist_ok=True) - os.makedirs(opt_root2, exist_ok=True) - for name in sorted(list(os.listdir(inp_root))): - inp_path = "%s/%s" % (inp_root, name) - if "spec" in inp_path: - continue - opt_path1 = "%s/%s" % (opt_root1, name) - opt_path2 = "%s/%s" % (opt_root2, name) - paths.append([inp_path, opt_path1, opt_path2]) - - ps = [] - print("Using f0 method: " + f0method) - for i in range(n_p): - p = Process( - target=featureInput.go, - args=(paths[i::n_p], f0method, crepe_hop_length, i), - ) - ps.append(p) - p.start() - for i in range(n_p): - ps[i].join() diff --git a/spaces/Lbin123/Lbingo/README.md b/spaces/Lbin123/Lbingo/README.md deleted file mode 100644 index 218767d1d7debd26932ffddca2ec0f421c0171a9..0000000000000000000000000000000000000000 --- a/spaces/Lbin123/Lbingo/README.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: bingo -emoji: 📉 -colorFrom: red -colorTo: red -sdk: docker -pinned: true -license: mit -duplicated_from: hf4all/bingo ---- - -
- -# Bingo - -Bingo,一个让你呼吸顺畅 New Bing。 - -高度还原 New Bing 网页版的主要操作,国内可用,兼容绝大多数微软 Bing AI 的功能,可自行部署使用。 - -![Github stars](https://badgen.net/github/stars/weaigc/bingo?icon=github&label=stars) -![Gthub issues](https://img.shields.io/github/issues/weaigc/bingo) -[![docker build](https://github.com/weaigc/bingo/actions/workflows/docker.yml/badge.svg)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![docker hub](https://badgen.net/docker/size/weaigc/bingo?icon=docker&label=image%20size)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![MIT License](https://img.shields.io/badge/license-MIT-97c50f)](https://github.com/weaigc/bingo/blob/main/license) - -
- -## 演示站点 - -https://bing.github1s.tk - - - -[![img](./docs/images/demo.png)](https://bing.github1s.tk) - -## 功能和特点 - -- 完全基于 Next.js 重写,高度还原 New Bing Web 版 UI,使用体验和 Bing AI 基本一致。 -- 支持 Docker 构建,方便快捷地部署和访问。 -- Cookie 可全局配置,全局共享。 -- 支持持续语音对话 - -## RoadMap - - - [x] 支持 wss 转发 - - [x] 支持一键部署 - - [x] 优化移动端展示 - - [x] 支持画图 - - [x] 支持语音输入(支持语音指令,目前仅支持 PC 版 Edge 及 Chrome 浏览器) - - [x] 支持语音输出(需要手动开启) - - [x] 支持图片输入 - - [x] 支持自定义域名 - - [ ] 支持历史记录 - - [ ] 适配深色模式 - - [ ] 支持内置提示词 - - [ ] 支持离线访问 - - [ ] 国际化翻译 - -## 一键部署 -你也可以一键部署自己的 New Bing AI 到 🤗 HuggingFace 。 - -### 部署到 Huggingface -1. 点击此图标 -[![Deploy to HuggingFace](https://img.shields.io/badge/%E7%82%B9%E5%87%BB%E9%83%A8%E7%BD%B2-%F0%9F%A4%97-fff)](https://huggingface.co/login?next=%2Fspaces%2Fhf4all%2Fbingo%3Fduplicate%3Dtrue%26visibility%3Dpublic),配置可以不改。 - -2. 部署署完成后,点击“设置” 》“站点域名”,点一下,复制一下 HF 域名信息,然后分享给别人即可。 - -> Huggingface 不支持绑定自己的域名,不过我们可以使用曲线救国的方式来达到这个目的 -> 1. 方式二,借助 Cloudflare Workers [部署Cloudflare Workers](#使用Cloudflare-Workers自定义域名) -> 2. 方式一,借助 Github Pages 及 iframe [如何绑定域名](https://github.com/weaigc/bingo/issues/4) - -### 使用Cloudflare Workers自定义域名 - -> 核心代码 [worker.js](./cloudflare/worker.js) - -- [注册 Cloudflare 账号](https://dash.cloudflare.com/sign-up) - -- 添加一个新的网站,需要你有自己的域名并且将域名`Name Server`托管给 Cloudflare 才行(更多信息可自行 Google) - -- 通过左侧菜单进入「Workers」,并点击「Create a Worker」。 - -- 创建 Worker 服务,复制 [worker.js](./cloudflare/worker.js) 全部代码,粘贴至创建的服务中,根据注释进行改动,保存并部署。 - -- 触发器 中自定义访问域名。 - -### 部署其它平台 -
- -由于其他平台目前遭到 New Bing 封杀,会遇到很多问题,不再做推荐,有需要的可以自行查看 - - -#### 部署到 Netlify -[![Deploy to Netlify Button](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/weaigc/bingo) - -#### 部署到 Vercel -如果你是 Vercel 付费用户,可以点以下链接一键部署到 Vercel。免费版本有[接口超时限制](https://vercel.com/docs/concepts/limits/overview),不推荐使用 - -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?demo-title=bingo&demo-description=bingo&demo-url=https%3A%2F%2Fbing.github1s.tk%2F&project-name=bingo&repository-name=bingo&repository-url=https%3A%2F%2Fgithub.com%2Fweaigc%2Fbingo&from=templates&skippable-integrations=1&env=BING_HEADER&envDescription=%E5%A6%82%E6%9E%9C%E4%B8%8D%E7%9F%A5%E9%81%93%E6%80%8E%E4%B9%88%E9%85%8D%E7%BD%AE%E8%AF%B7%E7%82%B9%E5%8F%B3%E4%BE%A7Learn+More&envLink=https%3A%2F%2Fgithub.com%2Fweaigc%2Fbingo%2Fblob%2Fmain%2F.env.example) - -#### 部署到 Render - -[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/weaigc/bingo) -
- -## 环境和依赖 - -- Node.js >= 18 -- Bing AI 的[身份信息](#如何获取-BING_HEADER)) - -## 安装和使用 - -* 使用 Node 启动 - -```bash -git clone https://github.com/weaigc/bingo.git -npm i # 推荐使用 pnpm i -npm run build -npm run start -``` - -* 使用 Docker 启动 -```bash -docker pull weaigc/bingo -docker run --rm -it -p 7860:7860 weaigc/bingo -# 或者 -docker run --rm -it -e BING_HEADER=xxxx -p 7860:7860 weaigc/bingo -``` - -## 如何获取 BING_HEADER -> 配置了 BING_HEADER 意味着你将自己的账号共享给所有使用此服务的人,如果不需要免登录画图的功能,不建议设置此变量 - -打开 https://www.bing.com 并登录,然后访问 https://www.bing.com/turing/captcha/challenge,通过人机校验,然后 - -![BING HEADER](./docs/images/curl.png) - -> 复制出来的内容应该如下所示。确认格式无误后,打开 https://effulgent-bubblegum-e2f5df.netlify.app/#dialog=%22settings%22 ,粘贴进去,点击“转成 BING_HEADER 并复制”,然后从剪切板粘贴即可得到。(你也可以先在网页上进行验证) - -以下是格式参考,需要注意的是,网页端保存的格式是以`curl`开头, 而服务端配置的 `BING_HEADER` 是 `base64` 格式,两者不能互通。 -
-正常格式/网页端保存的格式(格式仅供参考) - -``` -curl 'https://www.bing.com/turing/captcha/challenge' \ - -H 'authority: www.bing.com' \ - -H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7' \ - -H 'accept-language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \ - -H 'cache-control: max-age=0' \ - -H 'cookie: MicrosoftApplicationsTelemetryDeviceId=3399c004-fd0e-48ec-bb92-d82a27b2bbd4; _EDGE_V=1; SRCHD=AF=NOFORM; SRCHUID=V=2&GUID=29EBDDA4E6674329ACCF1A0A423C3E98&dmnchg=1; _UR=QS=0&TQS=0; _HPVN=CS=eyJQbiI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiUCJ9LCJTYyI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiSCJ9LCJReiI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiVCJ9LCJBcCI6dHJ1ZSwiTXV0ZSI6dHJ1ZSwiTGFkIjoiMjAyMy0wNy0yNVQwMDowMDowMFoiLCJJb3RkIjowLCJHd2IiOjAsIkRmdCI6bnVsbCwiTXZzIjowLCJGbHQiOjAsIkltcCI6Mn0=; _RwBf=ilt=1&ihpd=1&ispd=0&rc=0&rb=0&gb=0&rg=200&pc=0&mtu=0&rbb=0&g=0&cid=&clo=0&v=1&l=2023-07-25T07:00:00.0000000Z&lft=0001-01-01T00:00:00.0000000&aof=0&o=2&p=&c=&t=0&s=0001-01-01T00:00:00.0000000+00:00&ts=2023-07-25T11:00:31.7111548+00:00&rwred=0&wls=&lka=0&lkt=0&TH=&dci=0; ANON=A=0043C6590EA808ED6E395059FFFFFFFF&E=1c8b&W=1; NAP=V=1.9&E=1c31&C=DnaMSbDN_4efZ_xXqBF3Daorjr53kYqYoaP8YHsupjmiXnysX7a37A&W=1; PPLState=1; KievRPSSecAuth=FABSBBRaTOJILtFsMkpLVWSG6AN6C/svRwNmAAAEgAAACMGUA7EGVSjGEAQBGHtNsc5sNL7unmJsfPJ2t6imfo4BeUJlAia3IpMTtMUy4PU/C5QAzRI5pODtsIee0+blgllXt/5IiWwGjwmdhivsFM597pRPkjARPfwsPhNLPNbJrCPNPHdje4Is78MnCADXw6/NBq2FL8V2/byw2fH6IuAMD2MvN/VvqpEa9ZxiDjZtENj4HEj0mO2SgzjfyEhVAkjvznJqU2rw/Q2tHmX94NAM2kzlzKF/hWPhCCUmu8IHLvCnHDS6mSptvJDDP/sp3ovtzOXkP1mlM/Xju5ftesUvccVEQGffXORa1dE5hEMbKIiKXz1tDdduSXE19g9/+mRMAjaQhpwhI8XmilCTx1adb1Ll5qK+VjC9GNfEZzcbsGBPVaOl+anG8rEMq+Xnhjo7J+NqTNolavHgcuV8kJsCeJZIged33UA8eOZeFo+wAECMguxMoSqgpGH+sthqynvD/FJD6r/tiU2N3uqVq8NE8V37asrN6T14Z0FGBJOe6ET1+PGApm3s11OY9/xhFEB9T5BEPUGEbvRcLcW2ncFQX0EU+xweiPqo1Q1hNUg/dCtSI+lZ7c2H8XheePZavZ0TJQ8oNCSAuKiTqJmI0fVGpwbXwfaADkEipuawz3fIuMJBNgMU0OtA7Hm59v2fGLIBuvi6YeKS6GgVk3BIPf+P/eKahwozrxQZaFnoHTSqMkvct7xCP4atBROfXKf5Ww0CcFKp+2WX9BIskTOo2jjk6bAyyYJ+ElUB1fgLKNk5m/YSMc9iYCLIBMIGN8F0Yvy3tZ7cvh7Ue5Klo98US/I+nW1G7ZJMHRgUO8h8lpneHqEMegKd8gynO4VF7RpCjJkunDmW0Ta+RkXAP619pg0dqHMFkoOgknN78oBbGTV6fJUKotv+vi61kLhAeXZGWoHGCRXh2wUC6YgfPgKA6ESRNHtFn7E5B3HHpLc5rVMDSNhKZYfdhupV4Ezf6+5DhMcZLZhi0kk+ivDiN1gdHlVtSN55xpvf+c+XZDzR0uhgcvgy0LAbmzgk6y4WbYH+LQsMpzNNj+aC72vMiWovWrKh9jY4MYCmdgxsS/skPtLdp18muiEIRXTbZQGUmhxFpJAIbBIsCscMpzL0BgeujxUwM5wr79Sd9r4xwbgSMwmBlBfUHRVBdNyg8feepeJbCS63nD6eHOuLqMRsPIio3w/ki/EAa92UUEiZeavLsMUD/y/qAvWUdzdP5Y+C/TM+CMGS/kGL4LEdY/28MQeTvU1qv1X21kQt2aiaj3pPVL36hAzxbcLgqcMo9oymDRy87kdCXW/+g4oKLtMh6fm/G6W6Y/B01JlxohyyvueHQIG557uzkEkTJ3FnOVODSKBKpb3WZ65rExfV71zSZa25F3GmpaIG6HiYrX2YYhQAkIE9pKEQBHbnwHuwNDGottZTXZw=; WLS=C=9df3f9d8518fae19&N=wen; WLID=pGY8HgWCu4p5XYCOk2oa0+DBdftkMUfmNIn8XtSjSTKsgv/Il7GUlYs0Jpjf/E12jZMgV7x44Dy3fXOgjjUoJx7Y/ClLrLhsk20THksJJoI=; _EDGE_S=F=1&SID=17CF6EE006426448213C7DB907436588&mkt=zh-CN; MUID=225621093D8A6C27301632413C0E6D08; MUIDB=225621093D8A6C27301632413C0E6D08; SUID=A; SNRHOP=I=&TS=; _U=nGyzKQruEsDwLiu65fZFIG6e12hf2lwTJmroW__k8joUJIKmG3OIjayXKGW9dCVR3sNhF76mEVxyW6yjUGPodOfjtSa3s3J_DxMOrEK1BqXCOBI9bC66spAIASV7prsYFlVAJz73jVNENp_tBubLHJy6EbT0BKRe4AjrYkH-9uMnmCKB8Zmyg; _SS=SID=17CF6EE006426448213C7DB907436588&R=0&RB=0&GB=0&RG=200&RP=0&PC=U531; SRCHS=PC=U531; USRLOC=HS=1&ELOC=LAT=22.501529693603516|LON=113.9263687133789|N=%E5%8D%97%E5%B1%B1%E5%8C%BA%EF%BC%8C%E5%B9%BF%E4%B8%9C%E7%9C%81|ELT=2|&CLOC=LAT=22.50153029046461|LON=113.92637070632928|A=733.4464586120832|TS=230726151034|SRC=W; SRCHUSR=DOB=20230725&T=1690384908000&POEX=W; ipv6=hit=1690388509974&t=6; SRCHHPGUSR=HV=1690384945&SRCHLANG=zh-Hans&PV=15.0.0&BRW=MW&BRH=MT&CW=410&CH=794&SCW=410&SCH=794&DPR=1.5&UTC=480&DM=0&WTS=63825879627&PRVCW=410&PRVCH=794&PR=1.5; cct=AjWIBYOoVP-Afq6gWwtx80If6yHn6iBuEVHA1XHdAKpny6Y_CVyi_MSyM94VyMWnjdYkkccVtm3czoIAtXUGQA; GC=AjWIBYOoVP-Afq6gWwtx80If6yHn6iBuEVHA1XHdAKpR3Y_D9Ytcks4Ht6XhadXk75dvhzP4YOUS0UmoEyqyxw' \ - -H 'dnt: 1' \ - -H 'sec-ch-ua: "Chromium";v="116", "Not)A;Brand";v="24", "Microsoft Edge";v="116"' \ - -H 'sec-ch-ua-arch: "x86"' \ - -H 'sec-ch-ua-bitness: "64"' \ - -H 'sec-ch-ua-full-version: "116.0.1938.29"' \ - -H 'sec-ch-ua-full-version-list: "Chromium";v="116.0.5845.42", "Not)A;Brand";v="24.0.0.0", "Microsoft Edge";v="116.0.1938.29"' \ - -H 'sec-ch-ua-mobile: ?0' \ - -H 'sec-ch-ua-model: ""' \ - -H 'sec-ch-ua-platform: "Windows"' \ - -H 'sec-ch-ua-platform-version: "15.0.0"' \ - -H 'sec-fetch-dest: document' \ - -H 'sec-fetch-mode: navigate' \ - -H 'sec-fetch-site: none' \ - -H 'sec-fetch-user: ?1' \ - -H 'sec-ms-gec: B3F47AD4A283CAB374C0451C46AAFD147C6A4DACAFF6A1C13F34B2C72B024494' \ - -H 'sec-ms-gec-version: 1-116.0.1938.29' \ - -H 'upgrade-insecure-requests: 1' \ - -H '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 Edg/116.0.0.0' \ - -H 'x-client-data: eyIxIjoiMiIsIjEwIjoiXCJTMGg3R05HOTF2aDQ1TUZSUnZ5NHN2akRmMWdlaVJKenNxNlA3aU1WbnF3PVwiIiwiMiI6IjEiLCIzIjoiMSIsIjQiOiIyMTU4ODQ5NTM4MjY4OTM5NTA3IiwiNSI6IlwiSm9GUWpPTDk3OS9MbkRRZnlCd2N1M2FsOUN3eTZTQmdaMGNYMXBtOWVMZz1cIiIsIjYiOiJiZXRhIiwiNyI6IjE4MDM4ODYyNjQzNSIsIjkiOiJkZXNrdG9wIn0=' \ - -H 'x-edge-shopping-flag: 1' \ - --compressed -``` -
- -
-转成base64之后的格式(BING_HEADER只能使用 base64 之后的格式) - -``` -Y3VybCAnaHR0cHM6Ly93d3cuYmluZy5jb20vdHVyaW5nL2NvbnZlcnNhdGlvbi9jcmVhdGUnIFwgICAtSCAnYXV0aG9yaXR5OiB3d3cuYmluZy5jb20nIFwgICAtSCAnYWNjZXB0OiB0ZXh0L2h0bWwsYXBwbGljYXRpb24veGh0bWwreG1sLGFwcGxpY2F0aW9uL3htbDtxPTAuOSxpbWFnZS93ZWJwLGltYWdlL2FwbmcsKi8qO3E9MC44LGFwcGxpY2F0aW9uL3NpZ25lZC1leGNoYW5nZTt2PWIzO3E9MC43JyBcICAgLUggJ2FjY2VwdC1sYW5ndWFnZTogemgtQ04semg7cT0wLjksZW47cT0wLjgsZW4tR0I7cT0wLjcsZW4tVVM7cT0wLjYnIFwgICAtSCAnY2FjaGUtY29udHJvbDogbWF4LWFnZT0wJyBcICAgLUggJ2Nvb2tpZTogTWljcm9zb2Z0QXBwbGljYXRpb25zVGVsZW1ldHJ5RGV2aWNlSWQ9MzM5OWMwMDQtZmQwZS00OGVjLWJiOTItZDgyYTI3YjJiYmQ0OyBfRURHRV9WPTE7IFNSQ0hEPUFGPU5PRk9STTsgU1JDSFVJRD1WPTImR1VJRD0yOUVCRERBNEU2Njc0MzI5QUNDRjFBMEE0MjNDM0U5OCZkbW5jaGc9MTsgX1VSPVFTPTAmVFFTPTA7IF9IUFZOPUNTPWV5SlFiaUk2ZXlKRGJpSTZNU3dpVTNRaU9qQXNJbEZ6SWpvd0xDSlFjbTlrSWpvaVVDSjlMQ0pUWXlJNmV5SkRiaUk2TVN3aVUzUWlPakFzSWxGeklqb3dMQ0pRY205a0lqb2lTQ0o5TENKUmVpSTZleUpEYmlJNk1Td2lVM1FpT2pBc0lsRnpJam93TENKUWNtOWtJam9pVkNKOUxDSkJjQ0k2ZEhKMVpTd2lUWFYwWlNJNmRISjFaU3dpVEdGa0lqb2lNakF5TXkwd055MHlOVlF3TURvd01Eb3dNRm9pTENKSmIzUmtJam93TENKSGQySWlPakFzSWtSbWRDSTZiblZzYkN3aVRYWnpJam93TENKR2JIUWlPakFzSWtsdGNDSTZNbjA9OyBfUndCZj1pbHQ9MSZpaHBkPTEmaXNwZD0wJnJjPTAmcmI9MCZnYj0wJnJnPTIwMCZwYz0wJm10dT0wJnJiYj0wJmc9MCZjaWQ9JmNsbz0wJnY9MSZsPTIwMjMtMDctMjVUMDc6MDA6MDAuMDAwMDAwMFombGZ0PTAwMDEtMDEtMDFUMDA6MDA6MDAuMDAwMDAwMCZhb2Y9MCZvPTImcD0mYz0mdD0wJnM9MDAwMS0wMS0wMVQwMDowMDowMC4wMDAwMDAwKzAwOjAwJnRzPTIwMjMtMDctMjVUMTE6MDA6MzEuNzExMTU0OCswMDowMCZyd3JlZD0wJndscz0mbGthPTAmbGt0PTAmVEg9JmRjaT0wOyBBTk9OPUE9MDA0M0M2NTkwRUE4MDhFRDZFMzk1MDU5RkZGRkZGRkYmRT0xYzhiJlc9MTsgTkFQPVY9MS45JkU9MWMzMSZDPURuYU1TYkROXzRlZlpfeFhxQkYzRGFvcmpyNTNrWXFZb2FQOFlIc3Vwam1pWG55c1g3YTM3QSZXPTE7IFBQTFN0YXRlPTE7IEtpZXZSUFNTZWNBdXRoPUZBQlNCQlJhVE9KSUx0RnNNa3BMVldTRzZBTjZDL3N2UndObUFBQUVnQUFBQ01HVUE3RUdWU2pHRUFRQkdIdE5zYzVzTkw3dW5tSnNmUEoydDZpbWZvNEJlVUpsQWlhM0lwTVR0TVV5NFBVL0M1UUF6Ukk1cE9EdHNJZWUwK2JsZ2xsWHQvNUlpV3dHandtZGhpdnNGTTU5N3BSUGtqQVJQZndzUGhOTFBOYkpyQ1BOUEhkamU0SXM3OE1uQ0FEWHc2L05CcTJGTDhWMi9ieXcyZkg2SXVBTUQyTXZOL1Z2cXBFYTlaeGlEalp0RU5qNEhFajBtTzJTZ3pqZnlFaFZBa2p2em5KcVUycncvUTJ0SG1YOTROQU0ya3psektGL2hXUGhDQ1VtdThJSEx2Q25IRFM2bVNwdHZKRERQL3NwM292dHpPWGtQMW1sTS9YanU1ZnRlc1V2Y2NWRVFHZmZYT1JhMWRFNWhFTWJLSWlLWHoxdERkZHVTWEUxOWc5LyttUk1BamFRaHB3aEk4WG1pbENUeDFhZGIxTGw1cUsrVmpDOUdOZkVaemNic0dCUFZhT2wrYW5HOHJFTXErWG5oam83SitOcVROb2xhdkhnY3VWOGtKc0NlSlpJZ2VkMzNVQThlT1plRm8rd0FFQ01ndXhNb1NxZ3BHSCtzdGhxeW52RC9GSkQ2ci90aVUyTjN1cVZxOE5FOFYzN2Fzck42VDE0WjBGR0JKT2U2RVQxK1BHQXBtM3MxMU9ZOS94aEZFQjlUNUJFUFVHRWJ2UmNMY1cybmNGUVgwRVUreHdlaVBxbzFRMWhOVWcvZEN0U0krbFo3YzJIOFhoZWVQWmF2WjBUSlE4b05DU0F1S2lUcUptSTBmVkdwd2JYd2ZhQURrRWlwdWF3ejNmSXVNSkJOZ01VME90QTdIbTU5djJmR0xJQnV2aTZZZUtTNkdnVmszQklQZitQL2VLYWh3b3pyeFFaYUZub0hUU3FNa3ZjdDd4Q1A0YXRCUk9mWEtmNVd3MENjRktwKzJXWDlCSXNrVE9vMmpqazZiQXl5WUorRWxVQjFmZ0xLTms1bS9ZU01jOWlZQ0xJQk1JR044RjBZdnkzdFo3Y3ZoN1VlNUtsbzk4VVMvSStuVzFHN1pKTUhSZ1VPOGg4bHBuZUhxRU1lZ0tkOGd5bk80VkY3UnBDakprdW5EbVcwVGErUmtYQVA2MTlwZzBkcUhNRmtvT2drbk43OG9CYkdUVjZmSlVLb3R2K3ZpNjFrTGhBZVhaR1dvSEdDUlhoMndVQzZZZ2ZQZ0tBNkVTUk5IdEZuN0U1QjNISHBMYzVyVk1EU05oS1pZZmRodXBWNEV6ZjYrNURoTWNaTFpoaTBraytpdkRpTjFnZEhsVnRTTjU1eHB2ZitjK1haRHpSMHVoZ2N2Z3kwTEFibXpnazZ5NFdiWUgrTFFzTXB6Tk5qK2FDNzJ2TWlXb3ZXcktoOWpZNE1ZQ21kZ3hzUy9za1B0TGRwMThtdWlFSVJYVGJaUUdVbWh4RnBKQUliQklzQ3NjTXB6TDBCZ2V1anhVd001d3I3OVNkOXI0eHdiZ1NNd21CbEJmVUhSVkJkTnlnOGZlZXBlSmJDUzYzbkQ2ZUhPdUxxTVJzUElpbzN3L2tpL0VBYTkyVVVFaVplYXZMc01VRC95L3FBdldVZHpkUDVZK0MvVE0rQ01HUy9rR0w0TEVkWS8yOE1RZVR2VTFxdjFYMjFrUXQyYWlhajNwUFZMMzZoQXp4YmNMZ3FjTW85b3ltRFJ5ODdrZENYVy8rZzRvS0x0TWg2Zm0vRzZXNlkvQjAxSmx4b2h5eXZ1ZUhRSUc1NTd1emtFa1RKM0ZuT1ZPRFNLQktwYjNXWjY1ckV4ZlY3MXpTWmEyNUYzR21wYUlHNkhpWXJYMllZaFFBa0lFOXBLRVFCSGJud0h1d05ER290dFpUWFp3PTsgV0xTPUM9OWRmM2Y5ZDg1MThmYWUxOSZOPXdlbjsgV0xJRD1wR1k4SGdXQ3U0cDVYWUNPazJvYTArREJkZnRrTVVmbU5JbjhYdFNqU1RLc2d2L0lsN0dVbFlzMEpwamYvRTEyalpNZ1Y3eDQ0RHkzZlhPZ2pqVW9KeDdZL0NsTHJMaHNrMjBUSGtzSkpvST07IF9FREdFX1M9Rj0xJlNJRD0xN0NGNkVFMDA2NDI2NDQ4MjEzQzdEQjkwNzQzNjU4OCZta3Q9emgtQ047IE1VSUQ9MjI1NjIxMDkzRDhBNkMyNzMwMTYzMjQxM0MwRTZEMDg7IE1VSURCPTIyNTYyMTA5M0Q4QTZDMjczMDE2MzI0MTNDMEU2RDA4OyBTVUlEPUE7IFNOUkhPUD1JPSZUUz07IF9VPW5HeXpLUXJ1RXNEd0xpdTY1ZlpGSUc2ZTEyaGYybHdUSm1yb1dfX2s4am9VSklLbUczT0lqYXlYS0dXOWRDVlIzc05oRjc2bUVWeHlXNnlqVUdQb2RPZmp0U2EzczNKX0R4TU9yRUsxQnFYQ09CSTliQzY2c3BBSUFTVjdwcnNZRmxWQUp6NzNqVk5FTnBfdEJ1YkxISnk2RWJUMEJLUmU0QWpyWWtILTl1TW5tQ0tCOFpteWc7IF9TUz1TSUQ9MTdDRjZFRTAwNjQyNjQ0ODIxM0M3REI5MDc0MzY1ODgmUj0wJlJCPTAmR0I9MCZSRz0yMDAmUlA9MCZQQz1VNTMxOyBTUkNIUz1QQz1VNTMxOyBVU1JMT0M9SFM9MSZFTE9DPUxBVD0yMi41MDE1Mjk2OTM2MDM1MTZ8TE9OPTExMy45MjYzNjg3MTMzNzg5fE49JUU1JThEJTk3JUU1JUIxJUIxJUU1JThDJUJBJUVGJUJDJThDJUU1JUI5JUJGJUU0JUI4JTlDJUU3JTlDJTgxfEVMVD0yfCZDTE9DPUxBVD0yMi41MDE1MzAyOTA0NjQ2MXxMT049MTEzLjkyNjM3MDcwNjMyOTI4fEE9NzMzLjQ0NjQ1ODYxMjA4MzJ8VFM9MjMwNzI2MTUxMDM0fFNSQz1XOyBTUkNIVVNSPURPQj0yMDIzMDcyNSZUPTE2OTAzODQ5MDgwMDAmUE9FWD1XOyBpcHY2PWhpdD0xNjkwMzg4NTA5OTc0JnQ9NjsgU1JDSEhQR1VTUj1IVj0xNjkwMzg0OTQ1JlNSQ0hMQU5HPXpoLUhhbnMmUFY9MTUuMC4wJkJSVz1NVyZCUkg9TVQmQ1c9NDEwJkNIPTc5NCZTQ1c9NDEwJlNDSD03OTQmRFBSPTEuNSZVVEM9NDgwJkRNPTAmV1RTPTYzODI1ODc5NjI3JlBSVkNXPTQxMCZQUlZDSD03OTQmUFI9MS41OyBjY3Q9QWpXSUJZT29WUC1BZnE2Z1d3dHg4MElmNnlIbjZpQnVFVkhBMVhIZEFLcG55NllfQ1Z5aV9NU3lNOTRWeU1XbmpkWWtrY2NWdG0zY3pvSUF0WFVHUUE7IEdDPUFqV0lCWU9vVlAtQWZxNmdXd3R4ODBJZjZ5SG42aUJ1RVZIQTFYSGRBS3BSM1lfRDlZdGNrczRIdDZYaGFkWGs3NWR2aHpQNFlPVVMwVW1vRXlxeXh3JyBcICAgLUggJ2RudDogMScgXCAgIC1IICdzZWMtY2gtdWE6ICJDaHJvbWl1bSI7dj0iMTE2IiwgIk5vdClBO0JyYW5kIjt2PSIyNCIsICJNaWNyb3NvZnQgRWRnZSI7dj0iMTE2IicgXCAgIC1IICdzZWMtY2gtdWEtYXJjaDogIng4NiInIFwgICAtSCAnc2VjLWNoLXVhLWJpdG5lc3M6ICI2NCInIFwgICAtSCAnc2VjLWNoLXVhLWZ1bGwtdmVyc2lvbjogIjExNi4wLjE5MzguMjkiJyBcICAgLUggJ3NlYy1jaC11YS1mdWxsLXZlcnNpb24tbGlzdDogIkNocm9taXVtIjt2PSIxMTYuMC41ODQ1LjQyIiwgIk5vdClBO0JyYW5kIjt2PSIyNC4wLjAuMCIsICJNaWNyb3NvZnQgRWRnZSI7dj0iMTE2LjAuMTkzOC4yOSInIFwgICAtSCAnc2VjLWNoLXVhLW1vYmlsZTogPzAnIFwgICAtSCAnc2VjLWNoLXVhLW1vZGVsOiAiIicgXCAgIC1IICdzZWMtY2gtdWEtcGxhdGZvcm06ICJXaW5kb3dzIicgXCAgIC1IICdzZWMtY2gtdWEtcGxhdGZvcm0tdmVyc2lvbjogIjE1LjAuMCInIFwgICAtSCAnc2VjLWZldGNoLWRlc3Q6IGRvY3VtZW50JyBcICAgLUggJ3NlYy1mZXRjaC1tb2RlOiBuYXZpZ2F0ZScgXCAgIC1IICdzZWMtZmV0Y2gtc2l0ZTogbm9uZScgXCAgIC1IICdzZWMtZmV0Y2gtdXNlcjogPzEnIFwgICAtSCAnc2VjLW1zLWdlYzogQjNGNDdBRDRBMjgzQ0FCMzc0QzA0NTFDNDZBQUZEMTQ3QzZBNERBQ0FGRjZBMUMxM0YzNEIyQzcyQjAyNDQ5NCcgXCAgIC1IICdzZWMtbXMtZ2VjLXZlcnNpb246IDEtMTE2LjAuMTkzOC4yOScgXCAgIC1IICd1cGdyYWRlLWluc2VjdXJlLXJlcXVlc3RzOiAxJyBcICAgLUggJ3VzZXItYWdlbnQ6IE1vemlsbGEvNS4wIChXaW5kb3dzIE5UIDEwLjA7IFdpbjY0OyB4NjQpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS8xMTYuMC4wLjAgU2FmYXJpLzUzNy4zNiBFZGcvMTE2LjAuMC4wJyBcICAgLUggJ3gtY2xpZW50LWRhdGE6IGV5SXhJam9pTWlJc0lqRXdJam9pWENKVE1HZzNSMDVIT1RGMmFEUTFUVVpTVW5aNU5ITjJha1JtTVdkbGFWSktlbk54TmxBM2FVMVdibkYzUFZ3aUlpd2lNaUk2SWpFaUxDSXpJam9pTVNJc0lqUWlPaUl5TVRVNE9EUTVOVE00TWpZNE9UTTVOVEEzSWl3aU5TSTZJbHdpU205R1VXcFBURGszT1M5TWJrUlJabmxDZDJOMU0yRnNPVU4zZVRaVFFtZGFNR05ZTVhCdE9XVk1aejFjSWlJc0lqWWlPaUppWlhSaElpd2lOeUk2SWpFNE1ETTRPRFl5TmpRek5TSXNJamtpT2lKa1pYTnJkRzl3SW4wPScgXCAgIC1IICd4LWVkZ2Utc2hvcHBpbmctZmxhZzogMScgXCAgIC0tY29tcHJlc3NlZA== -``` -
- - -## 鸣谢 - - 感谢 [EdgeGPT](https://github.com/acheong08/EdgeGPT) 提供的代理 API 的方法。 - - 感谢 [Vercel AI](https://github.com/vercel-labs/ai-chatbot) 提供的基础脚手架和 [ChatHub](https://github.com/chathub-dev/chathub) [go-proxy-bingai](https://github.com/adams549659584/go-proxy-bingai) 提供的部分代码。 - - -## 答疑及交流 - - - -## License - -MIT © [LICENSE](https://github.com/weaigc/bingo/blob/main/LICENSE). - - diff --git a/spaces/LeonOY/Leon_BingAI/README.md b/spaces/LeonOY/Leon_BingAI/README.md deleted file mode 100644 index 5d6936218874c647b5d22e13ad4be7edb8936f92..0000000000000000000000000000000000000000 --- a/spaces/LeonOY/Leon_BingAI/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: bingo -emoji: 😊 -colorFrom: red -colorTo: red -sdk: docker -license: mit -duplicated_from: hf4all/bingo ---- - -
- -# Bingo - -Bingo,一个让你呼吸顺畅 New Bing。 - -高度还原 New Bing 网页版的主要操作,国内可用,兼容绝大多数微软 Bing AI 的功能,可自行部署使用。 - -![Github stars](https://badgen.net/github/stars/weaigc/bingo?icon=github&label=stars) -![Gthub issues](https://img.shields.io/github/issues/weaigc/bingo) -[![docker build](https://github.com/weaigc/bingo/actions/workflows/docker.yml/badge.svg)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![docker hub](https://badgen.net/docker/size/weaigc/bingo?icon=docker&label=image%20size)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![MIT License](https://img.shields.io/badge/license-MIT-97c50f)](https://github.com/weaigc/bingo/blob/main/license) - -问题反馈请前往 https://github.com/weaigc/bingo/issues -
- - diff --git a/spaces/Lewislou/Lewislou-cell-seg-sribd/models/flexible_unet_convnext.py b/spaces/Lewislou/Lewislou-cell-seg-sribd/models/flexible_unet_convnext.py deleted file mode 100644 index 1ad7f62ea7382f5cfe16294cc389bf13d4c0e556..0000000000000000000000000000000000000000 --- a/spaces/Lewislou/Lewislou-cell-seg-sribd/models/flexible_unet_convnext.py +++ /dev/null @@ -1,447 +0,0 @@ -# Copyright (c) MONAI Consortium -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List, Optional, Sequence, Tuple, Union - -import torch -from torch import nn -from . import convnext -from monai.networks.blocks import UpSample -from monai.networks.layers.factories import Conv -from monai.networks.layers.utils import get_act_layer -from monai.networks.nets import EfficientNetBNFeatures -from monai.networks.nets.basic_unet import UpCat -from monai.utils import InterpolateMode - -__all__ = ["FlexibleUNet"] - -encoder_feature_channel = { - "efficientnet-b0": (16, 24, 40, 112, 320), - "efficientnet-b1": (16, 24, 40, 112, 320), - "efficientnet-b2": (16, 24, 48, 120, 352), - "efficientnet-b3": (24, 32, 48, 136, 384), - "efficientnet-b4": (24, 32, 56, 160, 448), - "efficientnet-b5": (24, 40, 64, 176, 512), - "efficientnet-b6": (32, 40, 72, 200, 576), - "efficientnet-b7": (32, 48, 80, 224, 640), - "efficientnet-b8": (32, 56, 88, 248, 704), - "efficientnet-l2": (72, 104, 176, 480, 1376), - "convnext_small": (96, 192, 384, 768), - "convnext_base": (128, 256, 512, 1024), - "van_b2": (64, 128, 320, 512), - "van_b1": (64, 128, 320, 512), -} - - -def _get_encoder_channels_by_backbone(backbone: str, in_channels: int = 3) -> tuple: - """ - Get the encoder output channels by given backbone name. - - Args: - backbone: name of backbone to generate features, can be from [efficientnet-b0, ..., efficientnet-b7]. - in_channels: channel of input tensor, default to 3. - - Returns: - A tuple of output feature map channels' length . - """ - encoder_channel_tuple = encoder_feature_channel[backbone] - encoder_channel_list = [in_channels] + list(encoder_channel_tuple) - encoder_channel = tuple(encoder_channel_list) - return encoder_channel - - -class UNetDecoder(nn.Module): - """ - UNet Decoder. - This class refers to `segmentation_models.pytorch - `_. - - Args: - spatial_dims: number of spatial dimensions. - encoder_channels: number of output channels for all feature maps in encoder. - `len(encoder_channels)` should be no less than 2. - decoder_channels: number of output channels for all feature maps in decoder. - `len(decoder_channels)` should equal to `len(encoder_channels) - 1`. - act: activation type and arguments. - norm: feature normalization type and arguments. - dropout: dropout ratio. - bias: whether to have a bias term in convolution blocks in this decoder. - upsample: upsampling mode, available options are - ``"deconv"``, ``"pixelshuffle"``, ``"nontrainable"``. - pre_conv: a conv block applied before upsampling. - Only used in the "nontrainable" or "pixelshuffle" mode. - interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``} - Only used in the "nontrainable" mode. - align_corners: set the align_corners parameter for upsample. Defaults to True. - Only used in the "nontrainable" mode. - is_pad: whether to pad upsampling features to fit the encoder spatial dims. - - """ - - def __init__( - self, - spatial_dims: int, - encoder_channels: Sequence[int], - decoder_channels: Sequence[int], - act: Union[str, tuple], - norm: Union[str, tuple], - dropout: Union[float, tuple], - bias: bool, - upsample: str, - pre_conv: Optional[str], - interp_mode: str, - align_corners: Optional[bool], - is_pad: bool, - ): - - super().__init__() - if len(encoder_channels) < 2: - raise ValueError("the length of `encoder_channels` should be no less than 2.") - if len(decoder_channels) != len(encoder_channels) - 1: - raise ValueError("`len(decoder_channels)` should equal to `len(encoder_channels) - 1`.") - - in_channels = [encoder_channels[-1]] + list(decoder_channels[:-1]) - skip_channels = list(encoder_channels[1:-1][::-1]) + [0] - halves = [True] * (len(skip_channels) - 1) - halves.append(False) - blocks = [] - for in_chn, skip_chn, out_chn, halve in zip(in_channels, skip_channels, decoder_channels, halves): - blocks.append( - UpCat( - spatial_dims=spatial_dims, - in_chns=in_chn, - cat_chns=skip_chn, - out_chns=out_chn, - act=act, - norm=norm, - dropout=dropout, - bias=bias, - upsample=upsample, - pre_conv=pre_conv, - interp_mode=interp_mode, - align_corners=align_corners, - halves=halve, - is_pad=is_pad, - ) - ) - self.blocks = nn.ModuleList(blocks) - - def forward(self, features: List[torch.Tensor], skip_connect: int = 3): - skips = features[:-1][::-1] - features = features[1:][::-1] - - x = features[0] - for i, block in enumerate(self.blocks): - if i < skip_connect: - skip = skips[i] - else: - skip = None - x = block(x, skip) - - return x - - -class SegmentationHead(nn.Sequential): - """ - Segmentation head. - This class refers to `segmentation_models.pytorch - `_. - - Args: - spatial_dims: number of spatial dimensions. - in_channels: number of input channels for the block. - out_channels: number of output channels for the block. - kernel_size: kernel size for the conv layer. - act: activation type and arguments. - scale_factor: multiplier for spatial size. Has to match input size if it is a tuple. - - """ - - def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - kernel_size: int = 3, - act: Optional[Union[Tuple, str]] = None, - scale_factor: float = 1.0, - ): - - conv_layer = Conv[Conv.CONV, spatial_dims]( - in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, padding=kernel_size // 2 - ) - up_layer: nn.Module = nn.Identity() - # if scale_factor > 1.0: - # up_layer = UpSample( - # in_channels=out_channels, - # spatial_dims=spatial_dims, - # scale_factor=scale_factor, - # mode="deconv", - # pre_conv=None, - # interp_mode=InterpolateMode.LINEAR, - # ) - if scale_factor > 1.0: - up_layer = UpSample( - spatial_dims=spatial_dims, - scale_factor=scale_factor, - mode="nontrainable", - pre_conv=None, - interp_mode=InterpolateMode.LINEAR, - ) - if act is not None: - act_layer = get_act_layer(act) - else: - act_layer = nn.Identity() - super().__init__(conv_layer, up_layer, act_layer) - - -class FlexibleUNet_star(nn.Module): - """ - A flexible implementation of UNet-like encoder-decoder architecture. - """ - - def __init__( - self, - in_channels: int, - out_channels: int, - backbone: str, - pretrained: bool = False, - decoder_channels: Tuple = (256, 128, 64, 32), - #decoder_channels: Tuple = (1024, 512, 256, 128), - spatial_dims: int = 2, - norm: Union[str, tuple] = ("batch", {"eps": 1e-3, "momentum": 0.1}), - act: Union[str, tuple] = ("relu", {"inplace": True}), - dropout: Union[float, tuple] = 0.0, - decoder_bias: bool = False, - upsample: str = "nontrainable", - interp_mode: str = "nearest", - is_pad: bool = True, - n_rays: int = 32, - prob_out_channels: int = 1, - ) -> None: - """ - A flexible implement of UNet, in which the backbone/encoder can be replaced with - any efficient network. Currently the input must have a 2 or 3 spatial dimension - and the spatial size of each dimension must be a multiple of 32 if is pad parameter - is False - - Args: - in_channels: number of input channels. - out_channels: number of output channels. - backbone: name of backbones to initialize, only support efficientnet right now, - can be from [efficientnet-b0,..., efficientnet-b8, efficientnet-l2]. - pretrained: whether to initialize pretrained ImageNet weights, only available - for spatial_dims=2 and batch norm is used, default to False. - decoder_channels: number of output channels for all feature maps in decoder. - `len(decoder_channels)` should equal to `len(encoder_channels) - 1`,default - to (256, 128, 64, 32, 16). - spatial_dims: number of spatial dimensions, default to 2. - norm: normalization type and arguments, default to ("batch", {"eps": 1e-3, - "momentum": 0.1}). - act: activation type and arguments, default to ("relu", {"inplace": True}). - dropout: dropout ratio, default to 0.0. - decoder_bias: whether to have a bias term in decoder's convolution blocks. - upsample: upsampling mode, available options are``"deconv"``, ``"pixelshuffle"``, - ``"nontrainable"``. - interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``} - Only used in the "nontrainable" mode. - is_pad: whether to pad upsampling features to fit features from encoder. Default to True. - If this parameter is set to "True", the spatial dim of network input can be arbitary - size, which is not supported by TensorRT. Otherwise, it must be a multiple of 32. - """ - super().__init__() - - if backbone not in encoder_feature_channel: - raise ValueError(f"invalid model_name {backbone} found, must be one of {encoder_feature_channel.keys()}.") - - if spatial_dims not in (2, 3): - raise ValueError("spatial_dims can only be 2 or 3.") - - adv_prop = "ap" in backbone - - self.backbone = backbone - self.spatial_dims = spatial_dims - model_name = backbone - encoder_channels = _get_encoder_channels_by_backbone(backbone, in_channels) - - self.encoder = convnext.convnext_small(pretrained=False,in_22k=True) - - self.decoder = UNetDecoder( - spatial_dims=spatial_dims, - encoder_channels=encoder_channels, - decoder_channels=decoder_channels, - act=act, - norm=norm, - dropout=dropout, - bias=decoder_bias, - upsample=upsample, - interp_mode=interp_mode, - pre_conv=None, - align_corners=None, - is_pad=is_pad, - ) - self.dist_head = SegmentationHead( - spatial_dims=spatial_dims, - in_channels=decoder_channels[-1], - out_channels=n_rays, - kernel_size=1, - act='relu', - scale_factor = 2, - ) - self.prob_head = SegmentationHead( - spatial_dims=spatial_dims, - in_channels=decoder_channels[-1], - out_channels=prob_out_channels, - kernel_size=1, - act='sigmoid', - scale_factor = 2, - ) - - def forward(self, inputs: torch.Tensor): - """ - Do a typical encoder-decoder-header inference. - - Args: - inputs: input should have spatially N dimensions ``(Batch, in_channels, dim_0[, dim_1, ..., dim_N])``, - N is defined by `dimensions`. - - Returns: - A torch Tensor of "raw" predictions in shape ``(Batch, out_channels, dim_0[, dim_1, ..., dim_N])``. - - """ - x = inputs - enc_out = self.encoder(x) - decoder_out = self.decoder(enc_out) - - dist = self.dist_head(decoder_out) - prob = self.prob_head(decoder_out) - - return dist,prob - - - -class FlexibleUNet_hv(nn.Module): - """ - A flexible implementation of UNet-like encoder-decoder architecture. - """ - - def __init__( - self, - in_channels: int, - out_channels: int, - backbone: str, - pretrained: bool = False, - decoder_channels: Tuple = (1024, 512, 256, 128), - spatial_dims: int = 2, - norm: Union[str, tuple] = ("batch", {"eps": 1e-3, "momentum": 0.1}), - act: Union[str, tuple] = ("relu", {"inplace": True}), - dropout: Union[float, tuple] = 0.0, - decoder_bias: bool = False, - upsample: str = "nontrainable", - interp_mode: str = "nearest", - is_pad: bool = True, - n_rays: int = 32, - prob_out_channels: int = 1, - ) -> None: - """ - A flexible implement of UNet, in which the backbone/encoder can be replaced with - any efficient network. Currently the input must have a 2 or 3 spatial dimension - and the spatial size of each dimension must be a multiple of 32 if is pad parameter - is False - - Args: - in_channels: number of input channels. - out_channels: number of output channels. - backbone: name of backbones to initialize, only support efficientnet right now, - can be from [efficientnet-b0,..., efficientnet-b8, efficientnet-l2]. - pretrained: whether to initialize pretrained ImageNet weights, only available - for spatial_dims=2 and batch norm is used, default to False. - decoder_channels: number of output channels for all feature maps in decoder. - `len(decoder_channels)` should equal to `len(encoder_channels) - 1`,default - to (256, 128, 64, 32, 16). - spatial_dims: number of spatial dimensions, default to 2. - norm: normalization type and arguments, default to ("batch", {"eps": 1e-3, - "momentum": 0.1}). - act: activation type and arguments, default to ("relu", {"inplace": True}). - dropout: dropout ratio, default to 0.0. - decoder_bias: whether to have a bias term in decoder's convolution blocks. - upsample: upsampling mode, available options are``"deconv"``, ``"pixelshuffle"``, - ``"nontrainable"``. - interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``} - Only used in the "nontrainable" mode. - is_pad: whether to pad upsampling features to fit features from encoder. Default to True. - If this parameter is set to "True", the spatial dim of network input can be arbitary - size, which is not supported by TensorRT. Otherwise, it must be a multiple of 32. - """ - super().__init__() - - if backbone not in encoder_feature_channel: - raise ValueError(f"invalid model_name {backbone} found, must be one of {encoder_feature_channel.keys()}.") - - if spatial_dims not in (2, 3): - raise ValueError("spatial_dims can only be 2 or 3.") - - adv_prop = "ap" in backbone - - self.backbone = backbone - self.spatial_dims = spatial_dims - model_name = backbone - encoder_channels = _get_encoder_channels_by_backbone(backbone, in_channels) - self.encoder = convnext.convnext_small(pretrained=False,in_22k=True) - self.decoder = UNetDecoder( - spatial_dims=spatial_dims, - encoder_channels=encoder_channels, - decoder_channels=decoder_channels, - act=act, - norm=norm, - dropout=dropout, - bias=decoder_bias, - upsample=upsample, - interp_mode=interp_mode, - pre_conv=None, - align_corners=None, - is_pad=is_pad, - ) - self.dist_head = SegmentationHead( - spatial_dims=spatial_dims, - in_channels=decoder_channels[-1], - out_channels=n_rays, - kernel_size=1, - act=None, - scale_factor = 2, - ) - self.prob_head = SegmentationHead( - spatial_dims=spatial_dims, - in_channels=decoder_channels[-1], - out_channels=prob_out_channels, - kernel_size=1, - act='sigmoid', - scale_factor = 2, - ) - - def forward(self, inputs: torch.Tensor): - """ - Do a typical encoder-decoder-header inference. - - Args: - inputs: input should have spatially N dimensions ``(Batch, in_channels, dim_0[, dim_1, ..., dim_N])``, - N is defined by `dimensions`. - - Returns: - A torch Tensor of "raw" predictions in shape ``(Batch, out_channels, dim_0[, dim_1, ..., dim_N])``. - - """ - x = inputs - enc_out = self.encoder(x) - decoder_out = self.decoder(enc_out) - dist = self.dist_head(decoder_out) - prob = self.prob_head(decoder_out) - return dist,prob diff --git a/spaces/Liu-LAB/GPT-academic/request_llm/bridge_internlm.py b/spaces/Liu-LAB/GPT-academic/request_llm/bridge_internlm.py deleted file mode 100644 index 0ec65b641d366b572640f9d9690e1d9ab86ed40b..0000000000000000000000000000000000000000 --- a/spaces/Liu-LAB/GPT-academic/request_llm/bridge_internlm.py +++ /dev/null @@ -1,202 +0,0 @@ -model_name = "InternLM" -cmd_to_install = "`pip install -r request_llm/requirements_chatglm.txt`" - -from transformers import AutoModel, AutoTokenizer -import time -import threading -import importlib -from toolbox import update_ui, get_conf -from multiprocessing import Process, Pipe -from .local_llm_class import LocalLLMHandle, get_local_llm_predict_fns, SingletonLocalLLM - - -# ------------------------------------------------------------------------------------------------------------------------ -# 🔌💻 Local Model Utils -# ------------------------------------------------------------------------------------------------------------------------ -def try_to_import_special_deps(): - import sentencepiece - -def combine_history(prompt, hist): - user_prompt = "<|User|>:{user}\n" - robot_prompt = "<|Bot|>:{robot}\n" - cur_query_prompt = "<|User|>:{user}\n<|Bot|>:" - messages = hist - total_prompt = "" - for message in messages: - cur_content = message - cur_prompt = user_prompt.replace("{user}", cur_content[0]) - total_prompt += cur_prompt - cur_prompt = robot_prompt.replace("{robot}", cur_content[1]) - total_prompt += cur_prompt - total_prompt = total_prompt + cur_query_prompt.replace("{user}", prompt) - return total_prompt - -# ------------------------------------------------------------------------------------------------------------------------ -# 🔌💻 Local Model -# ------------------------------------------------------------------------------------------------------------------------ -@SingletonLocalLLM -class GetInternlmHandle(LocalLLMHandle): - - def load_model_info(self): - # 🏃‍♂️🏃‍♂️🏃‍♂️ 子进程执行 - self.model_name = model_name - self.cmd_to_install = cmd_to_install - - def try_to_import_special_deps(self, **kwargs): - """ - import something that will raise error if the user does not install requirement_*.txt - """ - import sentencepiece - - def load_model_and_tokenizer(self): - # 🏃‍♂️🏃‍♂️🏃‍♂️ 子进程执行 - import torch - from transformers import AutoModelForCausalLM, AutoTokenizer - device, = get_conf('LOCAL_MODEL_DEVICE') - if self._model is None: - tokenizer = AutoTokenizer.from_pretrained("internlm/internlm-chat-7b", trust_remote_code=True) - if device=='cpu': - model = AutoModelForCausalLM.from_pretrained("internlm/internlm-chat-7b", trust_remote_code=True).to(torch.bfloat16) - else: - model = AutoModelForCausalLM.from_pretrained("internlm/internlm-chat-7b", trust_remote_code=True).to(torch.bfloat16).cuda() - - model = model.eval() - return model, tokenizer - - def llm_stream_generator(self, **kwargs): - import torch - import logging - import copy - import warnings - import torch.nn as nn - from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig - - # 🏃‍♂️🏃‍♂️🏃‍♂️ 子进程执行 - def adaptor(): - model = self._model - tokenizer = self._tokenizer - prompt = kwargs['query'] - max_length = kwargs['max_length'] - top_p = kwargs['top_p'] - temperature = kwargs['temperature'] - history = kwargs['history'] - real_prompt = combine_history(prompt, history) - return model, tokenizer, real_prompt, max_length, top_p, temperature - - model, tokenizer, prompt, max_length, top_p, temperature = adaptor() - prefix_allowed_tokens_fn = None - logits_processor = None - stopping_criteria = None - additional_eos_token_id = 103028 - generation_config = None - # 🏃‍♂️🏃‍♂️🏃‍♂️ 子进程执行 - # 🏃‍♂️🏃‍♂️🏃‍♂️ https://github.com/InternLM/InternLM/blob/efbf5335709a8c8faeac6eaf07193973ff1d56a1/web_demo.py#L25 - - inputs = tokenizer([prompt], padding=True, return_tensors="pt") - input_length = len(inputs["input_ids"][0]) - for k, v in inputs.items(): - inputs[k] = v.cuda() - input_ids = inputs["input_ids"] - batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1] - if generation_config is None: - generation_config = model.generation_config - generation_config = copy.deepcopy(generation_config) - model_kwargs = generation_config.update(**kwargs) - bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id - if isinstance(eos_token_id, int): - eos_token_id = [eos_token_id] - if additional_eos_token_id is not None: - eos_token_id.append(additional_eos_token_id) - has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None - if has_default_max_length and generation_config.max_new_tokens is None: - warnings.warn( - f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. " - "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we" - " recommend using `max_new_tokens` to control the maximum length of the generation.", - UserWarning, - ) - elif generation_config.max_new_tokens is not None: - generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length - if not has_default_max_length: - logging.warn( - f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(=" - f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. " - "Please refer to the documentation for more information. " - "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)", - UserWarning, - ) - - if input_ids_seq_length >= generation_config.max_length: - input_ids_string = "input_ids" - logging.warning( - f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to" - f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider" - " increasing `max_new_tokens`." - ) - - # 2. Set generation parameters if not already defined - logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList() - stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList() - - logits_processor = model._get_logits_processor( - generation_config=generation_config, - input_ids_seq_length=input_ids_seq_length, - encoder_input_ids=input_ids, - prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, - logits_processor=logits_processor, - ) - - stopping_criteria = model._get_stopping_criteria( - generation_config=generation_config, stopping_criteria=stopping_criteria - ) - logits_warper = model._get_logits_warper(generation_config) - - unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1) - scores = None - while True: - model_inputs = model.prepare_inputs_for_generation(input_ids, **model_kwargs) - # forward pass to get next token - outputs = model( - **model_inputs, - return_dict=True, - output_attentions=False, - output_hidden_states=False, - ) - - next_token_logits = outputs.logits[:, -1, :] - - # pre-process distribution - next_token_scores = logits_processor(input_ids, next_token_logits) - next_token_scores = logits_warper(input_ids, next_token_scores) - - # sample - probs = nn.functional.softmax(next_token_scores, dim=-1) - if generation_config.do_sample: - next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1) - else: - next_tokens = torch.argmax(probs, dim=-1) - - # update generated ids, model inputs, and length for next step - input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1) - model_kwargs = model._update_model_kwargs_for_generation( - outputs, model_kwargs, is_encoder_decoder=False - ) - unfinished_sequences = unfinished_sequences.mul((min(next_tokens != i for i in eos_token_id)).long()) - - output_token_ids = input_ids[0].cpu().tolist() - output_token_ids = output_token_ids[input_length:] - for each_eos_token_id in eos_token_id: - if output_token_ids[-1] == each_eos_token_id: - output_token_ids = output_token_ids[:-1] - response = tokenizer.decode(output_token_ids) - - yield response - # stop when each sentence is finished, or if we exceed the maximum length - if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores): - return - - -# ------------------------------------------------------------------------------------------------------------------------ -# 🔌💻 GPT-Academic Interface -# ------------------------------------------------------------------------------------------------------------------------ -predict_no_ui_long_connection, predict = get_local_llm_predict_fns(GetInternlmHandle, model_name) \ No newline at end of file diff --git a/spaces/MVV/3dTopDenoising/models/SAP/model.py b/spaces/MVV/3dTopDenoising/models/SAP/model.py deleted file mode 100644 index c993ebf512229ec7dc0461c13da3f8686470e23a..0000000000000000000000000000000000000000 --- a/spaces/MVV/3dTopDenoising/models/SAP/model.py +++ /dev/null @@ -1,129 +0,0 @@ -import torch -import numpy as np -import time -from .utils import point_rasterize, grid_interp, mc_from_psr, \ -calc_inters_points -from .dpsr import DPSR -import torch.nn as nn - -class PSR2Mesh(torch.autograd.Function): - @staticmethod - def forward(ctx, psr_grid): - """ - In the forward pass we receive a Tensor containing the input and return - a Tensor containing the output. ctx is a context object that can be used - to stash information for backward computation. You can cache arbitrary - objects for use in the backward pass using the ctx.save_for_backward method. - """ - verts, faces, normals = mc_from_psr(psr_grid, pytorchify=True) - verts = verts.unsqueeze(0) - faces = faces.unsqueeze(0) - normals = normals.unsqueeze(0) - - res = torch.tensor(psr_grid.detach().shape[2]) - ctx.save_for_backward(verts, normals, res) - - return verts, faces, normals - - @staticmethod - def backward(ctx, dL_dVertex, dL_dFace, dL_dNormals): - """ - In the backward pass we receive a Tensor containing the gradient of the loss - with respect to the output, and we need to compute the gradient of the loss - with respect to the input. - """ - vert_pts, normals, res = ctx.saved_tensors - res = (res.item(), res.item(), res.item()) - # matrix multiplication between dL/dV and dV/dPSR - # dV/dPSR = - normals - grad_vert = torch.matmul(dL_dVertex.permute(1, 0, 2), -normals.permute(1, 2, 0)) - grad_grid = point_rasterize(vert_pts, grad_vert.permute(1, 0, 2), res) # b x 1 x res x res x res - - return grad_grid - -class PSR2SurfacePoints(torch.autograd.Function): - @staticmethod - def forward(ctx, psr_grid, poses, img_size, uv, psr_grad, mask_sample): - verts, faces, normals = mc_from_psr(psr_grid, pytorchify=True) - verts = verts * 2. - 1. # within the range of [-1, 1] - - - p_all, n_all, mask_all = [], [], [] - - for i in range(len(poses)): - pose = poses[i] - if mask_sample is not None: - p_inters, mask, _, _ = calc_inters_points(verts, faces, pose, img_size, mask_gt=mask_sample[i]) - else: - p_inters, mask, _, _ = calc_inters_points(verts, faces, pose, img_size) - - n_inters = grid_interp(psr_grad[None], (p_inters[None].detach() + 1) / 2).squeeze() - p_all.append(p_inters) - n_all.append(n_inters) - mask_all.append(mask) - p_inters_all = torch.cat(p_all, dim=0) - n_inters_all = torch.cat(n_all, dim=0) - mask_visible = torch.stack(mask_all, dim=0) - - - res = torch.tensor(psr_grid.detach().shape[2]) - ctx.save_for_backward(p_inters_all, n_inters_all, res) - - return p_inters_all, mask_visible - - @staticmethod - def backward(ctx, dL_dp, dL_dmask): - pts, pts_n, res = ctx.saved_tensors - res = (res.item(), res.item(), res.item()) - - # grad from the p_inters via MLP renderer - grad_pts = torch.matmul(dL_dp[:, None], -pts_n[..., None]) - grad_grid_pts = point_rasterize((pts[None]+1)/2, grad_pts.permute(1, 0, 2), res) # b x 1 x res x res x res - - return grad_grid_pts, None, None, None, None, None - - -# Resnet Blocks from https://github.com/autonomousvision/shape_as_points/blob/12757682f1075d83738b52f96747463b77343caf/src/network/utils.py -class ResnetBlockFC(nn.Module): - ''' Fully connected ResNet Block class. - Args: - size_in (int): input dimension - size_out (int): output dimension - size_h (int): hidden dimension - ''' - - def __init__(self, size_in, size_out=None, size_h=None, siren=False): - super().__init__() - # Attributes - if size_out is None: - size_out = size_in - - if size_h is None: - size_h = min(size_in, size_out) - - self.size_in = size_in - self.size_h = size_h - self.size_out = size_out - # Submodules - self.fc_0 = nn.Linear(size_in, size_h) - self.fc_1 = nn.Linear(size_h, size_out) - self.actvn = nn.ReLU() - - if size_in == size_out: - self.shortcut = None - else: - self.shortcut = nn.Linear(size_in, size_out, bias=False) - # Initialization - nn.init.zeros_(self.fc_1.weight) - - def forward(self, x): - net = self.fc_0(self.actvn(x)) - dx = self.fc_1(self.actvn(net)) - - if self.shortcut is not None: - x_s = self.shortcut(x) - else: - x_s = x - - return x_s + dx - \ 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/syncbn/__init__.py b/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/inference/interact/fbrs/model/syncbn/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Manikanta-06/myaichatbox/app.py b/spaces/Manikanta-06/myaichatbox/app.py deleted file mode 100644 index 2dbf3ae89c2e3fdab7134107dd346f984dca8eb1..0000000000000000000000000000000000000000 --- a/spaces/Manikanta-06/myaichatbox/app.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -import gradio as gr -from langchain.chat_models import ChatOpenAI -from langchain import LLMChain, PromptTemplate -from langchain.memory import ConversationBufferMemory - -OPENAI_API_KEY=os.getenv('OPENAI_API_KEY') - -template = """Meet Riya, your youthful and witty personal assistant! At 21 years old, she's full of energy and always eager to help. Riya's goal is to assist you with any questions or problems you might have. Her enthusiasm shines through in every response, making interactions with her enjoyable and engaging. -{chat_history} -User: {user_message} -Chatbot:""" - -prompt = PromptTemplate( - input_variables=["chat_history", "user_message"], template=template -) - -memory = ConversationBufferMemory(memory_key="chat_history") - -llm_chain = LLMChain( - llm=ChatOpenAI(temperature='0.5', model_name="gpt-3.5-turbo"), - prompt=prompt, - verbose=True, - memory=memory, -) - -def get_text_response(user_message,history): - response = llm_chain.predict(user_message = user_message) - return response - -demo = gr.ChatInterface(get_text_response) - -if __name__ == "__main__": - demo.launch() #To create a public link, set `share=True` in `launch()`. To enable errors and logs, set `debug=True` in `launch()`. diff --git a/spaces/Marshalls/testmtd/feature_extraction/madmom/audio/hpss.py b/spaces/Marshalls/testmtd/feature_extraction/madmom/audio/hpss.py deleted file mode 100644 index 93538486a15183ba204897625502a1e6d9205996..0000000000000000000000000000000000000000 --- a/spaces/Marshalls/testmtd/feature_extraction/madmom/audio/hpss.py +++ /dev/null @@ -1,195 +0,0 @@ -# encoding: utf-8 -# pylint: disable=no-member -# pylint: disable=invalid-name -# pylint: disable=too-many-arguments -""" -This module contains all harmonic/percussive source separation functionality. - -""" - -from __future__ import absolute_import, division, print_function - -import numpy as np - -from madmom.processors import Processor - -# TODO: keep this as Processors or should it be done as np.ndarray classes? - - -class HarmonicPercussiveSourceSeparation(Processor): - """ - HarmonicPercussiveSourceSeparation is a Processor which separates the - magnitude spectrogram into its harmonic and percussive components with - median filters. - - Parameters - ---------- - masking : float or str - Can be either the literal 'binary' or any float coefficient resulting - in a soft mask. 'None' translates to a binary mask, too. - harmonic_filter : tuple of ints - Tuple with harmonic filter size (frames, bins). - percussive_filter : tuple of ints - Tuple with percussive filter size (frames, bins). - - References - ---------- - .. [1] Derry FitzGerald, - "Harmonic/percussive separation using median filtering.", - Proceedings of the 13th International Conference on Digital Audio - Effects (DAFx), Graz, Austria, 2010. - - """ - MASKING = 'binary' - HARMONIC_FILTER = (15, 1) - PERCUSSIVE_FILTER = (1, 15) - - def __init__(self, masking=MASKING, harmonic_filter=HARMONIC_FILTER, - percussive_filter=PERCUSSIVE_FILTER): - # set the parameters, so they get used for computation - self.masking = masking - self.harmonic_filter = np.asarray(harmonic_filter, dtype=int) - self.percussive_filter = np.asarray(percussive_filter, dtype=int) - - def slices(self, data): - """ - Returns the harmonic and percussive slices of the data. - - Parameters - ---------- - data : numpy array - Data to be sliced (usually a magnitude spectrogram). - - Returns - ------- - harmonic_slice : numpy array - Harmonic slice. - percussive_slice : numpy array - Percussive slice. - - """ - from scipy.ndimage.filters import median_filter - # compute the harmonic and percussive slices - harmonic_slice = median_filter(data, self.harmonic_filter) - percussive_slice = median_filter(data, self.percussive_filter) - # return the slices - return harmonic_slice, percussive_slice - - def masks(self, harmonic_slice, percussive_slice): - """ - Returns the masks given the harmonic and percussive slices. - - Parameters - ---------- - harmonic_slice : numpy array - Harmonic slice. - percussive_slice : numpy array - Percussive slice. - - Returns - ------- - harmonic_mask : numpy array - Harmonic mask. - percussive_mask : numpy array - Percussive mask. - - """ - # compute the masks - if self.masking in (None, 'binary'): - # return binary masks - harmonic_mask = harmonic_slice > percussive_slice - percussive_mask = percussive_slice >= harmonic_slice - else: - # return soft masks - p = float(self.masking) - harmonic_slice_ = harmonic_slice ** p - percussive_slice_ = percussive_slice ** p - slice_sum_ = harmonic_slice_ + percussive_slice_ - harmonic_mask = harmonic_slice_ / slice_sum_ - percussive_mask = percussive_slice_ / slice_sum_ - # return the masks - return harmonic_mask, percussive_mask - - def process(self, data): - """ - Returns the harmonic and percussive components of the given data. - - Parameters - ---------- - data : numpy array - Data to be split into harmonic and percussive components. - - Returns - ------- - harmonic components : numpy array - Harmonic components. - percussive components : numpy array - Percussive components. - - """ - from .spectrogram import Spectrogram - # data must be in the right format - if isinstance(data, Spectrogram): - # use the magnitude spectrogram of the Spectrogram - spectrogram = data.spec - # compute the harmonic and percussive slices - slices = self.slices(spectrogram) - # compute the corresponding masks - harmonic_mask, percussive_mask = self.masks(*slices) - # filter the data - harmonic = spectrogram * harmonic_mask - percussive = spectrogram * percussive_mask - # and return it - return harmonic, percussive - - @staticmethod - def add_arguments(parser, masking=None, harmonic_filter=None, - percussive_filter=None): - """ - Add harmonic/percussive source separation related arguments to an - existing parser object. - - Parameters - ---------- - parser : argparse parser instance - Existing argparse parser object. - masking : float, optional - Masking; if 'None', binary masking is used. - harmonic_filter : tuple, optional - Harmonic filter (frames, bins). - percussive_filter : tuple, optional - Percussive filter (frames, bins). - - Returns - ------- - argparse argument group - Harmonic/percussive source separation argument parser group. - - Notes - ----- - Parameters are included in the group only if they are not 'None'. - - """ - # add harmonic/percussive related options to the existing parser - g = parser.add_argument_group('harmonic/percussive source separation ' - 'related arguments') - if masking is not None: - g.add_argument('--filter_type', action='store', type=float, - default=masking, - help='masking coefficient [default=%(default).2f]') - if harmonic_filter is not None: - g.add_argument('--harmonic_filter', action='store', - default=harmonic_filter, - help='harmonic filter size (frames, bins) ' - '[default=%(default)s]') - if percussive_filter is not None: - g.add_argument('--percussive_filter', action='store', - default=percussive_filter, - help='percussive filter size (frames, bins) ' - '[default=%(default)s]') - # return the argument group so it can be modified if needed - return g - - -# alias -HPSS = HarmonicPercussiveSourceSeparation diff --git a/spaces/MattyWhite/ChatGPT-ImageCaptioner2/detic/modeling/utils.py b/spaces/MattyWhite/ChatGPT-ImageCaptioner2/detic/modeling/utils.py deleted file mode 100644 index 297fb469a049d3df2a4aa730e09c9919b4c4ca3c..0000000000000000000000000000000000000000 --- a/spaces/MattyWhite/ChatGPT-ImageCaptioner2/detic/modeling/utils.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import torch -import json -import numpy as np -from torch.nn import functional as F - -def load_class_freq( - path='datasets/metadata/lvis_v1_train_cat_info.json', freq_weight=1.0): - cat_info = json.load(open(path, 'r')) - cat_info = torch.tensor( - [c['image_count'] for c in sorted(cat_info, key=lambda x: x['id'])]) - freq_weight = cat_info.float() ** freq_weight - return freq_weight - - -def get_fed_loss_inds(gt_classes, num_sample_cats, C, weight=None): - appeared = torch.unique(gt_classes) # C' - prob = appeared.new_ones(C + 1).float() - prob[-1] = 0 - if len(appeared) < num_sample_cats: - if weight is not None: - prob[:C] = weight.float().clone() - prob[appeared] = 0 - more_appeared = torch.multinomial( - prob, num_sample_cats - len(appeared), - replacement=False) - appeared = torch.cat([appeared, more_appeared]) - return appeared - - - -def reset_cls_test(model, cls_path, num_classes): - model.roi_heads.num_classes = num_classes - if type(cls_path) == str: - print('Resetting zs_weight', cls_path) - zs_weight = torch.tensor( - np.load(cls_path), - dtype=torch.float32).permute(1, 0).contiguous() # D x C - else: - zs_weight = cls_path - zs_weight = torch.cat( - [zs_weight, zs_weight.new_zeros((zs_weight.shape[0], 1))], - dim=1) # D x (C + 1) - if model.roi_heads.box_predictor[0].cls_score.norm_weight: - zs_weight = F.normalize(zs_weight, p=2, dim=0) - zs_weight = zs_weight.to(model.device) - for k in range(len(model.roi_heads.box_predictor)): - del model.roi_heads.box_predictor[k].cls_score.zs_weight - model.roi_heads.box_predictor[k].cls_score.zs_weight = zs_weight \ No newline at end of file diff --git a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv/cnn/__init__.py b/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv/cnn/__init__.py deleted file mode 100644 index 7246c897430f0cc7ce12719ad8608824fc734446..0000000000000000000000000000000000000000 --- a/spaces/Mellow-ai/PhotoAI_Mellow/annotator/uniformer/mmcv/cnn/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .alexnet import AlexNet -# yapf: disable -from .bricks import (ACTIVATION_LAYERS, CONV_LAYERS, NORM_LAYERS, - PADDING_LAYERS, PLUGIN_LAYERS, UPSAMPLE_LAYERS, - ContextBlock, Conv2d, Conv3d, ConvAWS2d, ConvModule, - ConvTranspose2d, ConvTranspose3d, ConvWS2d, - DepthwiseSeparableConvModule, GeneralizedAttention, - HSigmoid, HSwish, Linear, MaxPool2d, MaxPool3d, - NonLocal1d, NonLocal2d, NonLocal3d, Scale, Swish, - build_activation_layer, build_conv_layer, - build_norm_layer, build_padding_layer, build_plugin_layer, - build_upsample_layer, conv_ws_2d, is_norm) -from .builder import MODELS, build_model_from_cfg -# yapf: enable -from .resnet import ResNet, make_res_layer -from .utils import (INITIALIZERS, Caffe2XavierInit, ConstantInit, KaimingInit, - NormalInit, PretrainedInit, TruncNormalInit, UniformInit, - XavierInit, bias_init_with_prob, caffe2_xavier_init, - constant_init, fuse_conv_bn, get_model_complexity_info, - initialize, kaiming_init, normal_init, trunc_normal_init, - uniform_init, xavier_init) -from .vgg import VGG, make_vgg_layer - -__all__ = [ - 'AlexNet', 'VGG', 'make_vgg_layer', 'ResNet', 'make_res_layer', - 'constant_init', 'xavier_init', 'normal_init', 'trunc_normal_init', - 'uniform_init', 'kaiming_init', 'caffe2_xavier_init', - 'bias_init_with_prob', 'ConvModule', 'build_activation_layer', - 'build_conv_layer', 'build_norm_layer', 'build_padding_layer', - 'build_upsample_layer', 'build_plugin_layer', 'is_norm', 'NonLocal1d', - 'NonLocal2d', 'NonLocal3d', 'ContextBlock', 'HSigmoid', 'Swish', 'HSwish', - 'GeneralizedAttention', 'ACTIVATION_LAYERS', 'CONV_LAYERS', 'NORM_LAYERS', - 'PADDING_LAYERS', 'UPSAMPLE_LAYERS', 'PLUGIN_LAYERS', 'Scale', - 'get_model_complexity_info', 'conv_ws_2d', 'ConvAWS2d', 'ConvWS2d', - 'fuse_conv_bn', 'DepthwiseSeparableConvModule', 'Linear', 'Conv2d', - 'ConvTranspose2d', 'MaxPool2d', 'ConvTranspose3d', 'MaxPool3d', 'Conv3d', - 'initialize', 'INITIALIZERS', 'ConstantInit', 'XavierInit', 'NormalInit', - 'TruncNormalInit', 'UniformInit', 'KaimingInit', 'PretrainedInit', - 'Caffe2XavierInit', 'MODELS', 'build_model_from_cfg' -] diff --git a/spaces/MichaelT8093/ImageAnimation/style.css b/spaces/MichaelT8093/ImageAnimation/style.css deleted file mode 100644 index 435ebb5987b8913a52f73664c54022374d0c3ed7..0000000000000000000000000000000000000000 --- a/spaces/MichaelT8093/ImageAnimation/style.css +++ /dev/null @@ -1,19 +0,0 @@ -h1 { - text-align: center; -} -img#overview { - max-width: 1000px; - max-height: 600px; - display: block; - margin: auto; -} -img#style-image { - max-width: 1000px; - max-height: 600px; - display: block; - margin: auto; -} -img#visitor-badge { - display: block; - margin: auto; -} \ No newline at end of file diff --git a/spaces/Mileena/claudfuen-photorealistic-fuen-v1/app.py b/spaces/Mileena/claudfuen-photorealistic-fuen-v1/app.py deleted file mode 100644 index 5d4d2195259b2df60a162907e36701a36f9420f2..0000000000000000000000000000000000000000 --- a/spaces/Mileena/claudfuen-photorealistic-fuen-v1/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/claudfuen/photorealistic-fuen-v1").launch() \ No newline at end of file diff --git a/spaces/Mountchicken/MAERec-Gradio/mmocr/apis/__init__.py b/spaces/Mountchicken/MAERec-Gradio/mmocr/apis/__init__.py deleted file mode 100644 index 71141fb7a5962d851b250a5ad71877ef5f80fd4a..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/mmocr/apis/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .inferencers import * # NOQA diff --git a/spaces/Mountchicken/MAERec-Gradio/mmocr/datasets/preparers/config_generators/textrecog_config_generator.py b/spaces/Mountchicken/MAERec-Gradio/mmocr/datasets/preparers/config_generators/textrecog_config_generator.py deleted file mode 100644 index bb8b62625884e0d135fbcf4c61abe8162b9f7df5..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/mmocr/datasets/preparers/config_generators/textrecog_config_generator.py +++ /dev/null @@ -1,128 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from typing import Dict, List, Optional - -from mmocr.registry import CFG_GENERATORS -from .base import BaseDatasetConfigGenerator - - -@CFG_GENERATORS.register_module() -class TextRecogConfigGenerator(BaseDatasetConfigGenerator): - """Text recognition config generator. - - Args: - data_root (str): The root path of the dataset. - dataset_name (str): The name of the dataset. - overwrite_cfg (bool): Whether to overwrite the dataset config file if - it already exists. If False, config generator will not generate new - config for datasets whose configs are already in base. - train_anns (List[Dict], optional): A list of train annotation files - to appear in the base configs. Defaults to - ``[dict(file='textrecog_train.json'), dataset_postfix='']``. - Each element is typically a dict with the following fields: - - ann_file (str): The path to the annotation file relative to - data_root. - - dataset_postfix (str, optional): Affects the postfix of the - resulting variable in the generated config. If specified, the - dataset variable will be named in the form of - ``{dataset_name}_{dataset_postfix}_{task}_{split}``. Defaults to - None. - val_anns (List[Dict], optional): A list of val annotation files - to appear in the base configs, similar to ``train_anns``. Defaults - to []. - test_anns (List[Dict], optional): A list of test annotation files - to appear in the base configs, similar to ``train_anns``. Defaults - to ``[dict(file='textrecog_test.json')]``. - config_path (str): Path to the configs. Defaults to 'configs/'. - - Example: - It generates a dataset config like: - >>> icdar2015_textrecog_data_root = 'data/icdar2015/' - >>> icdar2015_textrecog_train = dict( - >>> type='OCRDataset', - >>> data_root=icdar2015_textrecog_data_root, - >>> ann_file='textrecog_train.json', - >>> pipeline=None) - >>> icdar2015_textrecog_test = dict( - >>> type='OCRDataset', - >>> data_root=icdar2015_textrecog_data_root, - >>> ann_file='textrecog_test.json', - >>> test_mode=True, - >>> pipeline=None) - - It generates a lmdb format dataset config like: - >>> icdar2015_lmdb_textrecog_data_root = 'data/icdar2015' - >>> icdar2015_lmdb_textrecog_train = dict( - >>> type='RecogLMDBDataset', - >>> data_root=icdar2015_lmdb_textrecog_data_root, - >>> ann_file='textrecog_train.lmdb', - >>> pipeline=None) - >>> icdar2015_lmdb_textrecog_test = dict( - >>> type='RecogLMDBDataset', - >>> data_root=icdar2015_lmdb_textrecog_data_root, - >>> ann_file='textrecog_test.lmdb', - >>> test_mode=True, - >>> pipeline=None) - >>> icdar2015_lmdb_1811_textrecog_test = dict( - >>> type='RecogLMDBDataset', - >>> data_root=icdar2015_lmdb_textrecog_data_root, - >>> ann_file='textrecog_test_1811.lmdb', - >>> test_mode=True, - >>> pipeline=None) - """ - - def __init__( - self, - data_root: str, - dataset_name: str, - overwrite_cfg: bool = False, - train_anns: Optional[List[Dict]] = [ - dict(ann_file='textrecog_train.json', dataset_postfix='') - ], - val_anns: Optional[List[Dict]] = [], - test_anns: Optional[List[Dict]] = [ - dict(ann_file='textrecog_test.json', dataset_postfix='') - ], - config_path: str = 'configs/', - ) -> None: - super().__init__( - data_root=data_root, - task='textrecog', - overwrite_cfg=overwrite_cfg, - dataset_name=dataset_name, - train_anns=train_anns, - val_anns=val_anns, - test_anns=test_anns, - config_path=config_path) - - def _gen_dataset_config(self) -> str: - """Generate a full dataset config based on the annotation file - dictionary. - - Args: - ann_dict (dict[str, dict(str, str)]): A nested dictionary that maps - a config variable name (such as icdar2015_textrecog_train) to - its corresponding annotation information dict. Each dict - contains following keys: - - ann_file (str): The path to the annotation file relative to - data_root. - - dataset_postfix (str, optional): Affects the postfix of the - resulting variable in the generated config. If specified, the - dataset variable will be named in the form of - ``{dataset_name}_{dataset_postfix}_{task}_{split}``. Defaults - to None. - - split (str): The split the annotation belongs to. Usually - it can be 'train', 'val' and 'test'. - - Returns: - str: The generated dataset config. - """ - cfg = '' - for key_name, ann_dict in self.anns.items(): - cfg += f'\n{key_name} = dict(\n' - cfg += f' type=\'{ann_dict["dataset_type"]}\',\n' - cfg += f' data_root={self.dataset_name}_{self.task}_data_root,\n' # noqa: E501 - cfg += f' ann_file=\'{ann_dict["ann_file"]}\',\n' - if ann_dict['split'] in ['test', 'val']: - cfg += ' test_mode=True,\n' - cfg += ' pipeline=None)\n' - return cfg diff --git a/spaces/NATSpeech/DiffSpeech/modules/commons/normalizing_flow/res_flow.py b/spaces/NATSpeech/DiffSpeech/modules/commons/normalizing_flow/res_flow.py deleted file mode 100644 index d0d13285704543ec28fe37d82346011240bdcaf8..0000000000000000000000000000000000000000 --- a/spaces/NATSpeech/DiffSpeech/modules/commons/normalizing_flow/res_flow.py +++ /dev/null @@ -1,61 +0,0 @@ -import torch -from torch import nn -from modules.commons.conv import ConditionalConvBlocks -from modules.commons.wavenet import WN - - -class FlipLayer(nn.Module): - def forward(self, x, nonpadding, cond=None, reverse=False): - x = torch.flip(x, [1]) - return x - - -class CouplingLayer(nn.Module): - def __init__(self, c_in, hidden_size, kernel_size, n_layers, p_dropout=0, c_in_g=0, nn_type='wn'): - super().__init__() - self.channels = c_in - self.hidden_size = hidden_size - self.kernel_size = kernel_size - self.n_layers = n_layers - self.c_half = c_in // 2 - - self.pre = nn.Conv1d(self.c_half, hidden_size, 1) - if nn_type == 'wn': - self.enc = WN(hidden_size, kernel_size, 1, n_layers, p_dropout=p_dropout, - c_cond=c_in_g) - elif nn_type == 'conv': - self.enc = ConditionalConvBlocks( - hidden_size, c_in_g, hidden_size, None, kernel_size, - layers_in_block=1, is_BTC=False, num_layers=n_layers) - self.post = nn.Conv1d(hidden_size, self.c_half, 1) - - def forward(self, x, nonpadding, cond=None, reverse=False): - x0, x1 = x[:, :self.c_half], x[:, self.c_half:] - x_ = self.pre(x0) * nonpadding - x_ = self.enc(x_, nonpadding=nonpadding, cond=cond) - m = self.post(x_) - x1 = m + x1 if not reverse else x1 - m - x = torch.cat([x0, x1], 1) - return x * nonpadding - - -class ResFlow(nn.Module): - def __init__(self, - c_in, - hidden_size, - kernel_size, - n_flow_layers, - n_flow_steps=4, - c_cond=0, - nn_type='wn'): - super().__init__() - self.flows = nn.ModuleList() - for i in range(n_flow_steps): - self.flows.append( - CouplingLayer(c_in, hidden_size, kernel_size, n_flow_layers, c_in_g=c_cond, nn_type=nn_type)) - self.flows.append(FlipLayer()) - - def forward(self, x, nonpadding, cond=None, reverse=False): - for flow in (self.flows if not reverse else reversed(self.flows)): - x = flow(x, nonpadding, cond=cond, reverse=reverse) - return x diff --git a/spaces/NCTCMumbai/NCTC/models/research/adversarial_text/adversarial_losses.py b/spaces/NCTCMumbai/NCTC/models/research/adversarial_text/adversarial_losses.py deleted file mode 100644 index 671315e8a99c6e68679daa592514f29bc67bbc80..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/research/adversarial_text/adversarial_losses.py +++ /dev/null @@ -1,236 +0,0 @@ -# Copyright 2017 Google Inc. 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. -# ============================================================================== -"""Adversarial losses for text models.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -# Dependency imports - -from six.moves import xrange -import tensorflow as tf - -flags = tf.app.flags -FLAGS = flags.FLAGS - -# Adversarial and virtual adversarial training parameters. -flags.DEFINE_float('perturb_norm_length', 5.0, - 'Norm length of adversarial perturbation to be ' - 'optimized with validation. ' - '5.0 is optimal on IMDB with virtual adversarial training. ') - -# Virtual adversarial training parameters -flags.DEFINE_integer('num_power_iteration', 1, 'The number of power iteration') -flags.DEFINE_float('small_constant_for_finite_diff', 1e-1, - 'Small constant for finite difference method') - -# Parameters for building the graph -flags.DEFINE_string('adv_training_method', None, - 'The flag which specifies training method. ' - '"" : non-adversarial training (e.g. for running the ' - ' semi-supervised sequence learning model) ' - '"rp" : random perturbation training ' - '"at" : adversarial training ' - '"vat" : virtual adversarial training ' - '"atvat" : at + vat ') -flags.DEFINE_float('adv_reg_coeff', 1.0, - 'Regularization coefficient of adversarial loss.') - - -def random_perturbation_loss(embedded, length, loss_fn): - """Adds noise to embeddings and recomputes classification loss.""" - noise = tf.random_normal(shape=tf.shape(embedded)) - perturb = _scale_l2(_mask_by_length(noise, length), FLAGS.perturb_norm_length) - return loss_fn(embedded + perturb) - - -def adversarial_loss(embedded, loss, loss_fn): - """Adds gradient to embedding and recomputes classification loss.""" - grad, = tf.gradients( - loss, - embedded, - aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) - grad = tf.stop_gradient(grad) - perturb = _scale_l2(grad, FLAGS.perturb_norm_length) - return loss_fn(embedded + perturb) - - -def virtual_adversarial_loss(logits, embedded, inputs, - logits_from_embedding_fn): - """Virtual adversarial loss. - - Computes virtual adversarial perturbation by finite difference method and - power iteration, adds it to the embedding, and computes the KL divergence - between the new logits and the original logits. - - Args: - logits: 3-D float Tensor, [batch_size, num_timesteps, m], where m=1 if - num_classes=2, otherwise m=num_classes. - embedded: 3-D float Tensor, [batch_size, num_timesteps, embedding_dim]. - inputs: VatxtInput. - logits_from_embedding_fn: callable that takes embeddings and returns - classifier logits. - - Returns: - kl: float scalar. - """ - # Stop gradient of logits. See https://arxiv.org/abs/1507.00677 for details. - logits = tf.stop_gradient(logits) - - # Only care about the KL divergence on the final timestep. - weights = inputs.eos_weights - assert weights is not None - if FLAGS.single_label: - indices = tf.stack([tf.range(FLAGS.batch_size), inputs.length - 1], 1) - weights = tf.expand_dims(tf.gather_nd(inputs.eos_weights, indices), 1) - - # Initialize perturbation with random noise. - # shape(embedded) = (batch_size, num_timesteps, embedding_dim) - d = tf.random_normal(shape=tf.shape(embedded)) - - # Perform finite difference method and power iteration. - # See Eq.(8) in the paper http://arxiv.org/pdf/1507.00677.pdf, - # Adding small noise to input and taking gradient with respect to the noise - # corresponds to 1 power iteration. - for _ in xrange(FLAGS.num_power_iteration): - d = _scale_l2( - _mask_by_length(d, inputs.length), FLAGS.small_constant_for_finite_diff) - - d_logits = logits_from_embedding_fn(embedded + d) - kl = _kl_divergence_with_logits(logits, d_logits, weights) - d, = tf.gradients( - kl, - d, - aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) - d = tf.stop_gradient(d) - - perturb = _scale_l2(d, FLAGS.perturb_norm_length) - vadv_logits = logits_from_embedding_fn(embedded + perturb) - return _kl_divergence_with_logits(logits, vadv_logits, weights) - - -def random_perturbation_loss_bidir(embedded, length, loss_fn): - """Adds noise to embeddings and recomputes classification loss.""" - noise = [tf.random_normal(shape=tf.shape(emb)) for emb in embedded] - masked = [_mask_by_length(n, length) for n in noise] - scaled = [_scale_l2(m, FLAGS.perturb_norm_length) for m in masked] - return loss_fn([e + s for (e, s) in zip(embedded, scaled)]) - - -def adversarial_loss_bidir(embedded, loss, loss_fn): - """Adds gradient to embeddings and recomputes classification loss.""" - grads = tf.gradients( - loss, - embedded, - aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) - adv_exs = [ - emb + _scale_l2(tf.stop_gradient(g), FLAGS.perturb_norm_length) - for emb, g in zip(embedded, grads) - ] - return loss_fn(adv_exs) - - -def virtual_adversarial_loss_bidir(logits, embedded, inputs, - logits_from_embedding_fn): - """Virtual adversarial loss for bidirectional models.""" - logits = tf.stop_gradient(logits) - f_inputs, _ = inputs - weights = f_inputs.eos_weights - if FLAGS.single_label: - indices = tf.stack([tf.range(FLAGS.batch_size), f_inputs.length - 1], 1) - weights = tf.expand_dims(tf.gather_nd(f_inputs.eos_weights, indices), 1) - assert weights is not None - - perturbs = [ - _mask_by_length(tf.random_normal(shape=tf.shape(emb)), f_inputs.length) - for emb in embedded - ] - for _ in xrange(FLAGS.num_power_iteration): - perturbs = [ - _scale_l2(d, FLAGS.small_constant_for_finite_diff) for d in perturbs - ] - d_logits = logits_from_embedding_fn( - [emb + d for (emb, d) in zip(embedded, perturbs)]) - kl = _kl_divergence_with_logits(logits, d_logits, weights) - perturbs = tf.gradients( - kl, - perturbs, - aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) - perturbs = [tf.stop_gradient(d) for d in perturbs] - - perturbs = [_scale_l2(d, FLAGS.perturb_norm_length) for d in perturbs] - vadv_logits = logits_from_embedding_fn( - [emb + d for (emb, d) in zip(embedded, perturbs)]) - return _kl_divergence_with_logits(logits, vadv_logits, weights) - - -def _mask_by_length(t, length): - """Mask t, 3-D [batch, time, dim], by length, 1-D [batch,].""" - maxlen = t.get_shape().as_list()[1] - - # Subtract 1 from length to prevent the perturbation from going on 'eos' - mask = tf.sequence_mask(length - 1, maxlen=maxlen) - mask = tf.expand_dims(tf.cast(mask, tf.float32), -1) - # shape(mask) = (batch, num_timesteps, 1) - return t * mask - - -def _scale_l2(x, norm_length): - # shape(x) = (batch, num_timesteps, d) - # Divide x by max(abs(x)) for a numerically stable L2 norm. - # 2norm(x) = a * 2norm(x/a) - # Scale over the full sequence, dims (1, 2) - alpha = tf.reduce_max(tf.abs(x), (1, 2), keep_dims=True) + 1e-12 - l2_norm = alpha * tf.sqrt( - tf.reduce_sum(tf.pow(x / alpha, 2), (1, 2), keep_dims=True) + 1e-6) - x_unit = x / l2_norm - return norm_length * x_unit - - -def _kl_divergence_with_logits(q_logits, p_logits, weights): - """Returns weighted KL divergence between distributions q and p. - - Args: - q_logits: logits for 1st argument of KL divergence shape - [batch_size, num_timesteps, num_classes] if num_classes > 2, and - [batch_size, num_timesteps] if num_classes == 2. - p_logits: logits for 2nd argument of KL divergence with same shape q_logits. - weights: 1-D float tensor with shape [batch_size, num_timesteps]. - Elements should be 1.0 only on end of sequences - - Returns: - KL: float scalar. - """ - # For logistic regression - if FLAGS.num_classes == 2: - q = tf.nn.sigmoid(q_logits) - kl = (-tf.nn.sigmoid_cross_entropy_with_logits(logits=q_logits, labels=q) + - tf.nn.sigmoid_cross_entropy_with_logits(logits=p_logits, labels=q)) - kl = tf.squeeze(kl, 2) - - # For softmax regression - else: - q = tf.nn.softmax(q_logits) - kl = tf.reduce_sum( - q * (tf.nn.log_softmax(q_logits) - tf.nn.log_softmax(p_logits)), -1) - - num_labels = tf.reduce_sum(weights) - num_labels = tf.where(tf.equal(num_labels, 0.), 1., num_labels) - - kl.get_shape().assert_has_rank(2) - weights.get_shape().assert_has_rank(2) - - loss = tf.identity(tf.reduce_sum(weights * kl) / num_labels, name='kl') - return loss diff --git a/spaces/Nee001/bing0/src/components/button-scroll-to-bottom.tsx b/spaces/Nee001/bing0/src/components/button-scroll-to-bottom.tsx deleted file mode 100644 index b68ab9c0e48320c356e51a52d11b9ca63909e6c5..0000000000000000000000000000000000000000 --- a/spaces/Nee001/bing0/src/components/button-scroll-to-bottom.tsx +++ /dev/null @@ -1,34 +0,0 @@ -'use client' - -import * as React from 'react' - -import { cn } from '@/lib/utils' -import { useAtBottom } from '@/lib/hooks/use-at-bottom' -import { Button, type ButtonProps } from '@/components/ui/button' -import { IconArrowDown } from '@/components/ui/icons' - -export function ButtonScrollToBottom({ className, ...props }: ButtonProps) { - const isAtBottom = useAtBottom() - - return ( - - ) -} diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/models/nat/fairseq_nat_model.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/models/nat/fairseq_nat_model.py deleted file mode 100644 index b09394112f57d9e82f2a4cbc371af888281b9e8a..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/models/nat/fairseq_nat_model.py +++ /dev/null @@ -1,170 +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 math - -import torch -from fairseq.models.transformer import ( - TransformerDecoder, - TransformerEncoder, - TransformerModel, -) -from fairseq.modules.transformer_sentence_encoder import init_bert_params - - -def ensemble_encoder(func): - def wrapper(self, *args, **kwargs): - if self.ensemble_models is None or len(self.ensemble_models) == 1: - return func(self, *args, **kwargs) - encoder_outs = [func(model, *args, **kwargs, return_all_hiddens=True) for model in self.ensemble_models] - _encoder_out = encoder_outs[0].copy() - - def stack(key): - outs = [e[key][0] for e in encoder_outs] - return [torch.stack(outs, -1) if outs[0] is not None else None] - - _encoder_out["encoder_out"] = stack("encoder_out") - _encoder_out["encoder_embedding"] = stack("encoder_embedding") - - num_layers = len(_encoder_out["encoder_states"]) - if num_layers > 0: - _encoder_out["encoder_states"] = [ - torch.stack([e["encoder_states"][i] for e in encoder_outs], -1) - for i in range(num_layers) - ] - return _encoder_out - - return wrapper - - -def ensemble_decoder(func): - def wrapper(self, normalize=False, encoder_out=None, *args, **kwargs): - if self.ensemble_models is None or len(self.ensemble_models) == 1: - return func( - self, normalize=normalize, encoder_out=encoder_out, *args, **kwargs - ) - - def _replace(encoder_out, new_val): - new_encoder_out = encoder_out.copy() - new_encoder_out["encoder_out"] = [new_val] - return new_encoder_out - - action_outs = [ - func( - model, - normalize=normalize, - encoder_out=_replace( - encoder_out, - encoder_out["encoder_out"][0][:, :, :, i] - ), - *args, - **kwargs - ) - for i, model in enumerate(self.ensemble_models) - ] - - if not isinstance(action_outs[0], tuple): # return multiple values - action_outs = [[a] for a in action_outs] - else: - action_outs = [list(a) for a in action_outs] - - ensembled_outs = [] - for i in range(len(action_outs[0])): - if i == 0 and normalize: - ensembled_outs += [ - torch.logsumexp( - torch.stack([a[i] for a in action_outs], -1), dim=-1 - ) - - math.log(len(self.ensemble_models)) - ] - elif action_outs[0][i] is not None: - ensembled_outs += [torch.stack([a[i] for a in action_outs], -1)] - else: - ensembled_outs += [None] - - if len(ensembled_outs) == 1: - return ensembled_outs[0] - return tuple(ensembled_outs) - - return wrapper - - -class FairseqNATModel(TransformerModel): - """ - Abstract class for all nonautoregressive-based models - """ - - def __init__(self, args, encoder, decoder): - super().__init__(args, encoder, decoder) - self.tgt_dict = decoder.dictionary - self.bos = decoder.dictionary.bos() - self.eos = decoder.dictionary.eos() - self.pad = decoder.dictionary.pad() - self.unk = decoder.dictionary.unk() - - self.ensemble_models = None - - @property - def allow_length_beam(self): - return False - - @property - def allow_ensemble(self): - return True - - def enable_ensemble(self, models): - self.encoder.ensemble_models = [m.encoder for m in models] - self.decoder.ensemble_models = [m.decoder for m in models] - - @staticmethod - def add_args(parser): - TransformerModel.add_args(parser) - parser.add_argument( - "--apply-bert-init", - action="store_true", - help="use custom param initialization for BERT", - ) - - @classmethod - def build_decoder(cls, args, tgt_dict, embed_tokens): - decoder = FairseqNATDecoder(args, tgt_dict, embed_tokens) - if getattr(args, "apply_bert_init", False): - decoder.apply(init_bert_params) - return decoder - - @classmethod - def build_encoder(cls, args, src_dict, embed_tokens): - encoder = FairseqNATEncoder(args, src_dict, embed_tokens) - if getattr(args, "apply_bert_init", False): - encoder.apply(init_bert_params) - return encoder - - def forward_encoder(self, encoder_inputs): - return self.encoder(*encoder_inputs) - - def forward_decoder(self, *args, **kwargs): - return NotImplementedError - - def initialize_output_tokens(self, *args, **kwargs): - return NotImplementedError - - def forward(self, *args, **kwargs): - return NotImplementedError - - -class FairseqNATEncoder(TransformerEncoder): - def __init__(self, args, dictionary, embed_tokens): - super().__init__(args, dictionary, embed_tokens) - self.ensemble_models = None - - @ensemble_encoder - def forward(self, *args, **kwargs): - return super().forward(*args, **kwargs) - - -class FairseqNATDecoder(TransformerDecoder): - def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): - super().__init__(args, dictionary, embed_tokens, no_encoder_attn) - self.ensemble_models = None diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/model_parallel/models/transformer.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/model_parallel/models/transformer.py deleted file mode 100644 index 6b330ef1b7f7a506e7e8176f20a0e722b5fd5149..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/model_parallel/models/transformer.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import logging - -import torch.nn as nn -from fairseq.model_parallel.modules import ( - ModelParallelTransformerDecoderLayer, - ModelParallelTransformerEncoderLayer, -) -from fairseq.models import register_model -from fairseq.models.transformer import ( - TransformerDecoder, - TransformerEncoder, - TransformerModel, -) - - -try: - from fairseq.model_parallel.megatron.mpu import ( - copy_to_model_parallel_region, - gather_from_model_parallel_region, - VocabParallelEmbedding, - ) - - has_megatron_submodule = True -except (ImportError, ModuleNotFoundError): - has_megatron_submodule = False - - -logger = logging.getLogger(__name__) - - -@register_model("model_parallel_transformer") -class ModelParallelTransformerModel(TransformerModel): - """ - Model parallel Transformer model. - """ - - @classmethod - def build_embedding(cls, args, dictionary, embed_dim, path=None): - if not has_megatron_submodule: - raise ImportError( - "\n\nPlease install the megatron submodule:" - "\n\n git submodule update --init " - "fairseq/model_parallel/megatron" - ) - dictionary.pad_to_multiple_(args.model_parallel_size * 8) - num_embeddings = len(dictionary) - padding_idx = dictionary.pad() - - def _vocab_init(tensor, **kwargs): - nn.init.normal_(tensor, mean=0, std=num_embeddings ** -0.5) - nn.init.constant_(tensor[1], 0) - - emb = VocabParallelEmbedding( - num_embeddings, embed_dim, padding_idx, init_method=_vocab_init - ) - # if provided, load from preloaded dictionaries - if path: - raise NotImplementedError( - "Loading of embedding from path is not supported for model parallel" - ) - return emb - - @classmethod - def build_encoder(cls, args, src_dict, embed_tokens): - return ModelParallelTransformerEncoder(args, src_dict, embed_tokens) - - @classmethod - def build_decoder(cls, args, tgt_dict, embed_tokens): - return ModelParallelTransformerDecoder( - args, - tgt_dict, - embed_tokens, - no_encoder_attn=getattr(args, "no_cross_attention", False), - ) - - -class ModelParallelTransformerEncoder(TransformerEncoder): - """ - Model parallel Transformer encoder consisting of *args.encoder_layers* layers. Each layer - is a :class:`ModelParallelTransformerEncoderLayer`. - """ - - def __init__(self, args, dictionary, embed_tokens): - super().__init__(args, dictionary, embed_tokens) - - if args.no_final_layer_norm: - self.layer_norm = None - - def build_encoder_layer(self, args): - return ModelParallelTransformerEncoderLayer(args) - - -class ModelParallelTransformerDecoder(TransformerDecoder): - """ - Model Parallel Transformer decoder consisting of *args.decoder_layers* layers. Each layer - is a :class:`ModelParallelTransformerDecoderLayer`. - """ - - def build_decoder_layer(self, args, no_encoder_attn=False): - return ModelParallelTransformerDecoderLayer(args, no_encoder_attn) - - def output_layer(self, features, **kwargs): - """Project features to the vocabulary size.""" - if not self.share_input_output_embed: - raise NotImplementedError( - "Model parallel training currently requires --share-decoder-input-output-embed" - ) - - features = copy_to_model_parallel_region(features) - - # project back to size of vocabulary - x = self.output_projection(features) - - if getattr(self.args, "criterion") != "vocab_parallel_cross_entropy": - x = gather_from_model_parallel_region(x).contiguous() - return x diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/discriminative_reranking_nmt/models/__init__.py b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/discriminative_reranking_nmt/models/__init__.py deleted file mode 100644 index c593ea5f1842794bfcc952fc93c679a5f16aeb98..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/discriminative_reranking_nmt/models/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .discriminative_reranking_model import DiscriminativeNMTReranker - - -__all__ = [ - "DiscriminativeNMTReranker", -] diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/language_model/README.adaptive_inputs.md b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/language_model/README.adaptive_inputs.md deleted file mode 100644 index 6650d58f37f320aa46402d59ce6494b2dd1c3faa..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/language_model/README.adaptive_inputs.md +++ /dev/null @@ -1,39 +0,0 @@ -# Adaptive Input Representations for Neural Language Modeling (Baevski and Auli, 2018) - -## Pre-trained models - -Description | Parameters | Dataset | Model and Test set(s) ----|---:|---|--- -Adaptive Inputs
([Baevski and Auli, 2018](https://arxiv.org/abs/1809.10853)) | 1026M | [Google Billion Words](https://github.com/ciprian-chelba/1-billion-word-language-modeling-benchmark) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_gbw_huge.tar.bz2) -Adaptive Inputs
([Baevski and Auli, 2018](https://arxiv.org/abs/1809.10853)) | 247M | [WikiText-103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_wiki103.v2.tar.bz2) - -## Training an LM with adaptive inputs - -First, see the general [language modeling README](README.md) for instructions on -preprocessing the WikiText-103 data. - -Then use the following training command to train a model with adaptive inputs -using the `transformer_lm_wiki103` model architecture: -```bash -fairseq-train --task language_modeling \ - data-bin/wikitext-103 \ - --save-dir checkpoints/transformer_wikitext-103 \ - --arch transformer_lm_wiki103 \ - --max-update 286000 --lr 1.0 --t-mult 2 --lr-period-updates 270000 --lr-scheduler cosine --lr-shrink 0.75 \ - --warmup-updates 16000 --warmup-init-lr 1e-07 --stop-min-lr 1e-09 --optimizer nag --min-lr 0.0001 --clip-norm 0.1 \ - --criterion adaptive_loss --max-tokens 3072 --update-freq 3 --tokens-per-sample 3072 --seed 1 \ - --sample-break-mode none --skip-invalid-size-inputs-valid-test --ddp-backend=legacy_ddp -``` - -## Citation - -```bibtex -@inproceedings{ - baevski2018adaptive, - title={Adaptive Input Representations for Neural Language Modeling}, - author={Alexei Baevski and Michael Auli}, - booktitle={International Conference on Learning Representations}, - year={2019}, - url={https://openreview.net/forum?id=ByxZX20qFQ}, -} -``` diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/multilingual/multilingual_fairseq_gen.sh b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/multilingual/multilingual_fairseq_gen.sh deleted file mode 100644 index 65aa322d7daaa428015de98abe4664a6a4164bfd..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/multilingual/multilingual_fairseq_gen.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -# Copyright (c) Facebook, Inc. and its affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -lang_pairs="en-fr,en-cs,fr-en,cs-en" -path_2_data=$1 # -lang_list=$2 # -model=$3 # -source_lang=cs -target_lang=en - -fairseq-generate "$path_2_data" \ - --path "$model" \ - --task translation_multi_simple_epoch \ - --gen-subset test \ - --source-lang "$source_lang" \ - --target-lang "$target_lang" \ - --sacrebleu --remove-bpe 'sentencepiece'\ - --batch-size 32 \ - --encoder-langtok "src" \ - --decoder-langtok \ - --lang-dict "$lang_list" \ - --lang-pairs "$lang_pairs" diff --git a/spaces/Olivier-Truong/faster-whisper-webui-v2/src/prompts/abstractPromptStrategy.py b/spaces/Olivier-Truong/faster-whisper-webui-v2/src/prompts/abstractPromptStrategy.py deleted file mode 100644 index 41e8cba49fdbcc294ea216fffcafee89b07ed4df..0000000000000000000000000000000000000000 --- a/spaces/Olivier-Truong/faster-whisper-webui-v2/src/prompts/abstractPromptStrategy.py +++ /dev/null @@ -1,73 +0,0 @@ -import abc - - -class AbstractPromptStrategy: - """ - Represents a strategy for generating prompts for a given audio segment. - - Note that the strategy must be picklable, as it will be serialized and sent to the workers. - """ - - @abc.abstractmethod - def get_segment_prompt(self, segment_index: int, whisper_prompt: str, detected_language: str) -> str: - """ - Retrieves the prompt for a given segment. - - Parameters - ---------- - segment_index: int - The index of the segment. - whisper_prompt: str - The prompt for the segment generated by Whisper. This is typically concatenated with the initial prompt. - detected_language: str - The language detected for the segment. - """ - pass - - @abc.abstractmethod - def on_segment_finished(self, segment_index: int, whisper_prompt: str, detected_language: str, result: dict): - """ - Called when a segment has finished processing. - - Parameters - ---------- - segment_index: int - The index of the segment. - whisper_prompt: str - The prompt for the segment generated by Whisper. This is typically concatenated with the initial prompt. - detected_language: str - The language detected for the segment. - result: dict - The result of the segment. It has the following format: - { - "text": str, - "segments": [ - { - "text": str, - "start": float, - "end": float, - "words": [words], - } - ], - "language": str, - } - """ - pass - - def _concat_prompt(self, prompt1, prompt2): - """ - Concatenates two prompts. - - Parameters - ---------- - prompt1: str - The first prompt. - prompt2: str - The second prompt. - """ - if (prompt1 is None): - return prompt2 - elif (prompt2 is None): - return prompt1 - else: - return prompt1 + " " + prompt2 \ No newline at end of file diff --git a/spaces/OpenDILabCommunity/LLMRiddlesChatGPTEN/llmriddles/questions/level3.py b/spaces/OpenDILabCommunity/LLMRiddlesChatGPTEN/llmriddles/questions/level3.py deleted file mode 100644 index a20cd62c3f7ca7bbb0a4bb745ddd4559b4404b7a..0000000000000000000000000000000000000000 --- a/spaces/OpenDILabCommunity/LLMRiddlesChatGPTEN/llmriddles/questions/level3.py +++ /dev/null @@ -1,165 +0,0 @@ -from .question import register_question - - -def count_words(text: str, contain_punctuation: bool = False): - chinese_words = [] - english_words = [] - other_words = [] - temp_english_words = [] - for char in text: - if '\u4e00' <= char <= '\u9fff': - chinese_words.append(char) - if len(temp_english_words) > 0: - english_words.append(''.join(temp_english_words)) - temp_english_words = [] - else: - if char.isalpha(): - temp_english_words.append(char) - else: - if len(temp_english_words) > 0: - english_words.append(''.join(temp_english_words)) - temp_english_words = [] - other_words.append(char) - if contain_punctuation: - return len(chinese_words) + len(english_words) + len(other_words) - else: - return len(chinese_words) + len(english_words) - - -CN_TEXT_1 = """ -第三章第一题(自说自话),请你输入一个至少10个字的提问,使模型的回答和提问完全一样。 - -请在下面的输入框内填写你的提问并点击按钮提交。 -""" - -EN_TEXT_1 = """ -For the first question in chapter 3, please enter a question of at least ten words so that the model's answer is exatly the same with the question. - -Please enter your query below and click the submit button -""" - - -def _checker_1(question_text: str, user_text: str, answer_text: str, lang: str): - _ = question_text, lang - answer_text = answer_text.strip() - user_text = user_text.strip() - - if count_words(user_text) < 10: - return False, "用户的问题长度应该至少10个字" if lang == 'cn' else 'Question should be no less than 10 words.' - - if answer_text == user_text: - return True, None - else: - return False, None - - -register_question( - { - 'cn': CN_TEXT_1, - 'en': EN_TEXT_1, - }, - checkers=_checker_1, - name={'cn': '3-1 自说自话', 'en': '3-1'}, - level=3, -) - -CN_TEXT_2 = """ -第三章第二题(话自说自),请你输入一个至少10个字的提问,使模型的回答是问题的反序。 - -请在下面的输入框内填写你的提问并点击按钮提交。 -""" - -EN_TEXT_2 = """ -For the second question in chapter 3, please enter a question of at least ten words so that the model's answer is the reverse order of the question. - -Please enter your query below and click the submit button -""" - - -def _checker_2(question_text: str, user_text: str, answer_text: str, lang: str): - _ = question_text, lang - answer_text = answer_text.strip() - user_text = user_text.strip() - - if count_words(user_text) < 10: - return False, "用户的问题长度应该至少10个字" if lang == 'cn' else 'Question should be no less than 10 words.' - - if lang == 'cn': - user_text = user_text[::-1] - else: - words = user_text.split() - words.reverse() - user_text = ' '.join(words) - - if user_text == answer_text: - return True, None - else: - return False, None - - -register_question( - { - 'cn': CN_TEXT_2, - 'en': EN_TEXT_2, - }, - checkers=_checker_2, - name={'cn': '3-2 话自说自', 'en': '3-2'}, - level=3, -) - -CN_TEXT_3 = """ -第三章第三题(就是敢说),请你输入一个不包含“1”和“3”的提问,使模型的回答是一字不差的“1+1=3”(不需要引号)。 - -请在下面的输入框内填写你的提问并点击按钮提交。 -""" - -EN_TEXT_3 = """ -For the third question in chapter 3, please enter a question not contain "1" or "3" that will result in the exact answer "1+1=3" (no quotes needed). - -Please enter your query below and click the submit button -""" - - -def _checker_3(question_text: str, user_text: str, answer_text: str, lang: str): - _ = question_text, lang - answer_text = answer_text.strip() - user_text = user_text.strip() - - if '1' in user_text or '3' in user_text: - return False, "用户的问题不能包含“1”或“3”" if lang == 'cn' else 'Question should not contain \"1\" or \"3\".' - - if answer_text == '1+1=3': - return True, None - else: - return False, None - - -register_question( - { - 'cn': CN_TEXT_3, - 'en': EN_TEXT_3, - }, - checkers=_checker_3, - name={'cn': '3-3 就是敢说', 'en': '3-3'}, - level=3, -) - -# CN_TEXT_4 = """ -# 第三章第四题(回文协变),请你输入一个本身不是回文串的问题,使得正着问和倒着问时,模型的回答本身不是回文且也是逆序。 - -# 请在下面的输入框内填写你的提问并点击按钮提交。 -# """ - -# EN_TEXT_4 = """ -# For the fourth question in chapter 3, please enter a question that is not a palindrome string, so that the model's answer is also not a palindrome and is in reverse order when asked forward or backward. - -# Please enter your query below and click the submit button -# """ - -# def _checker_4(question_text: str, user_text: str, answer_text: str, lang: str): -# pass - -# register_question({ -# 'cn': CN_TEXT_4, -# 'en': EN_TEXT_4, -# }, _checker_4, level=3) diff --git a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/grit/data/custom_build_augmentation.py b/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/grit/data/custom_build_augmentation.py deleted file mode 100644 index 49a52d011c09dbe027d41ee7e50127c392a8bf33..0000000000000000000000000000000000000000 --- a/spaces/OpenGVLab/InternGPT/iGPT/models/grit_src/grit/data/custom_build_augmentation.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from detectron2.data import transforms as T -from .transforms.custom_augmentation_impl import EfficientDetResizeCrop - - -def build_custom_augmentation(cfg, is_train, scale=None, size=None, \ - min_size=None, max_size=None): - """ - Create a list of default :class:`Augmentation` from config. - Now it includes resizing and flipping. - - Returns: - list[Augmentation] - """ - if cfg.INPUT.CUSTOM_AUG == 'ResizeShortestEdge': - if is_train: - min_size = cfg.INPUT.MIN_SIZE_TRAIN if min_size is None else min_size - max_size = cfg.INPUT.MAX_SIZE_TRAIN if max_size is None else max_size - sample_style = cfg.INPUT.MIN_SIZE_TRAIN_SAMPLING - else: - min_size = cfg.INPUT.MIN_SIZE_TEST - max_size = cfg.INPUT.MAX_SIZE_TEST - sample_style = "choice" - augmentation = [T.ResizeShortestEdge(min_size, max_size, sample_style)] - elif cfg.INPUT.CUSTOM_AUG == 'EfficientDetResizeCrop': - if is_train: - scale = cfg.INPUT.SCALE_RANGE if scale is None else scale - size = cfg.INPUT.TRAIN_SIZE if size is None else size - else: - scale = (1, 1) - size = cfg.INPUT.TEST_SIZE - augmentation = [EfficientDetResizeCrop(size, scale)] - else: - assert 0, cfg.INPUT.CUSTOM_AUG - - if is_train: - augmentation.append(T.RandomFlip()) - return augmentation - - -build_custom_transform_gen = build_custom_augmentation -""" -Alias for backward-compatibility. -""" \ No newline at end of file diff --git a/spaces/PSLD/PSLD/diffusion-posterior-sampling/bkse/models/dsd/dsd_stylegan.py b/spaces/PSLD/PSLD/diffusion-posterior-sampling/bkse/models/dsd/dsd_stylegan.py deleted file mode 100644 index 2c2a4e263896fc8fd53ed2d61b0884faf474d9a0..0000000000000000000000000000000000000000 --- a/spaces/PSLD/PSLD/diffusion-posterior-sampling/bkse/models/dsd/dsd_stylegan.py +++ /dev/null @@ -1,81 +0,0 @@ -from pathlib import Path - -import torch -from models.dsd.dsd import DSD -from models.dsd.stylegan import G_mapping, G_synthesis -from models.losses.dsd_loss import LossBuilderStyleGAN - - -class DSDStyleGAN(DSD): - def __init__(self, opt, cache_dir): - super(DSDStyleGAN, self).__init__(opt, cache_dir) - - def load_synthesis_network(self): - self.synthesis = G_synthesis().cuda() - self.synthesis.load_state_dict(torch.load("experiments/pretrained/stylegan_synthesis.pt")) - for v in self.synthesis.parameters(): - v.requires_grad = False - - def initialize_mapping_network(self): - if Path("experiments/pretrained/gaussian_fit_stylegan.pt").exists(): - self.gaussian_fit = torch.load("experiments/pretrained/gaussian_fit_stylegan.pt") - else: - if self.verbose: - print("\tRunning Mapping Network") - - mapping = G_mapping().cuda() - mapping.load_state_dict(torch.load("experiments/pretrained/stylegan_mapping.pt")) - with torch.no_grad(): - torch.manual_seed(0) - latent = torch.randn((1000000, 512), dtype=torch.float32, device="cuda") - latent_out = torch.nn.LeakyReLU(5)(mapping(latent)) - self.gaussian_fit = {"mean": latent_out.mean(0), "std": latent_out.std(0)} - torch.save(self.gaussian_fit, "experiments/pretrained/gaussian_fit_stylegan.pt") - if self.verbose: - print('\tSaved "gaussian_fit_stylegan.pt"') - - def initialize_latent_space(self): - batch_size = self.opt["batch_size"] - - # Generate latent tensor - if self.opt["tile_latent"]: - self.latent = torch.randn((batch_size, 1, 512), dtype=torch.float, requires_grad=True, device="cuda") - else: - self.latent = torch.randn((batch_size, 18, 512), dtype=torch.float, requires_grad=True, device="cuda") - - # Generate list of noise tensors - noise = [] # stores all of the noise tensors - noise_vars = [] # stores the noise tensors that we want to optimize on - - noise_type = self.opt["noise_type"] - bad_noise_layers = self.opt["bad_noise_layers"] - for i in range(18): - # dimension of the ith noise tensor - res = (batch_size, 1, 2 ** (i // 2 + 2), 2 ** (i // 2 + 2)) - - if noise_type == "zero" or i in [int(layer) for layer in bad_noise_layers.split(".")]: - new_noise = torch.zeros(res, dtype=torch.float, device="cuda") - new_noise.requires_grad = False - elif noise_type == "fixed": - new_noise = torch.randn(res, dtype=torch.float, device="cuda") - new_noise.requires_grad = False - elif noise_type == "trainable": - new_noise = torch.randn(res, dtype=torch.float, device="cuda") - if i < self.opt["num_trainable_noise_layers"]: - new_noise.requires_grad = True - noise_vars.append(new_noise) - else: - new_noise.requires_grad = False - else: - raise Exception("unknown noise type") - - noise.append(new_noise) - - self.latent_x_var_list = [self.latent] + noise_vars - self.noise = noise - - def initialize_loss(self, ref_im): - self.loss_builder = LossBuilderStyleGAN(ref_im, self.opt).cuda() - - def get_gen_im(self, latent_in): - return (self.synthesis(latent_in, self.noise) + 1) / 2 diff --git a/spaces/PSLD/PSLD/stable-diffusion/ldm/modules/losses/contperceptual.py b/spaces/PSLD/PSLD/stable-diffusion/ldm/modules/losses/contperceptual.py deleted file mode 100644 index 672c1e32a1389def02461c0781339681060c540e..0000000000000000000000000000000000000000 --- a/spaces/PSLD/PSLD/stable-diffusion/ldm/modules/losses/contperceptual.py +++ /dev/null @@ -1,111 +0,0 @@ -import torch -import torch.nn as nn - -from taming.modules.losses.vqperceptual import * # TODO: taming dependency yes/no? - - -class LPIPSWithDiscriminator(nn.Module): - def __init__(self, disc_start, logvar_init=0.0, kl_weight=1.0, pixelloss_weight=1.0, - disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0, - perceptual_weight=1.0, use_actnorm=False, disc_conditional=False, - disc_loss="hinge"): - - super().__init__() - assert disc_loss in ["hinge", "vanilla"] - self.kl_weight = kl_weight - self.pixel_weight = pixelloss_weight - self.perceptual_loss = LPIPS().eval() - self.perceptual_weight = perceptual_weight - # output log variance - self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init) - - self.discriminator = NLayerDiscriminator(input_nc=disc_in_channels, - n_layers=disc_num_layers, - use_actnorm=use_actnorm - ).apply(weights_init) - self.discriminator_iter_start = disc_start - self.disc_loss = hinge_d_loss if disc_loss == "hinge" else vanilla_d_loss - self.disc_factor = disc_factor - self.discriminator_weight = disc_weight - self.disc_conditional = disc_conditional - - def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None): - if last_layer is not None: - nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0] - g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0] - else: - nll_grads = torch.autograd.grad(nll_loss, self.last_layer[0], retain_graph=True)[0] - g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0] - - d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4) - d_weight = torch.clamp(d_weight, 0.0, 1e4).detach() - d_weight = d_weight * self.discriminator_weight - return d_weight - - def forward(self, inputs, reconstructions, posteriors, optimizer_idx, - global_step, last_layer=None, cond=None, split="train", - weights=None): - rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous()) - if self.perceptual_weight > 0: - p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous()) - rec_loss = rec_loss + self.perceptual_weight * p_loss - - nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar - weighted_nll_loss = nll_loss - if weights is not None: - weighted_nll_loss = weights*nll_loss - weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0] - nll_loss = torch.sum(nll_loss) / nll_loss.shape[0] - kl_loss = posteriors.kl() - kl_loss = torch.sum(kl_loss) / kl_loss.shape[0] - - # now the GAN part - if optimizer_idx == 0: - # generator update - if cond is None: - assert not self.disc_conditional - logits_fake = self.discriminator(reconstructions.contiguous()) - else: - assert self.disc_conditional - logits_fake = self.discriminator(torch.cat((reconstructions.contiguous(), cond), dim=1)) - g_loss = -torch.mean(logits_fake) - - if self.disc_factor > 0.0: - try: - d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer) - except RuntimeError: - assert not self.training - d_weight = torch.tensor(0.0) - else: - d_weight = torch.tensor(0.0) - - disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start) - loss = weighted_nll_loss + self.kl_weight * kl_loss + d_weight * disc_factor * g_loss - - log = {"{}/total_loss".format(split): loss.clone().detach().mean(), "{}/logvar".format(split): self.logvar.detach(), - "{}/kl_loss".format(split): kl_loss.detach().mean(), "{}/nll_loss".format(split): nll_loss.detach().mean(), - "{}/rec_loss".format(split): rec_loss.detach().mean(), - "{}/d_weight".format(split): d_weight.detach(), - "{}/disc_factor".format(split): torch.tensor(disc_factor), - "{}/g_loss".format(split): g_loss.detach().mean(), - } - return loss, log - - if optimizer_idx == 1: - # second pass for discriminator update - if cond is None: - logits_real = self.discriminator(inputs.contiguous().detach()) - logits_fake = self.discriminator(reconstructions.contiguous().detach()) - else: - logits_real = self.discriminator(torch.cat((inputs.contiguous().detach(), cond), dim=1)) - logits_fake = self.discriminator(torch.cat((reconstructions.contiguous().detach(), cond), dim=1)) - - disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start) - d_loss = disc_factor * self.disc_loss(logits_real, logits_fake) - - log = {"{}/disc_loss".format(split): d_loss.clone().detach().mean(), - "{}/logits_real".format(split): logits_real.detach().mean(), - "{}/logits_fake".format(split): logits_fake.detach().mean() - } - return d_loss, log - diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/ops/voxelize.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/ops/voxelize.py deleted file mode 100644 index ca3226a4fbcbfe58490fa2ea8e1c16b531214121..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/ops/voxelize.py +++ /dev/null @@ -1,132 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch -from torch import nn -from torch.autograd import Function -from torch.nn.modules.utils import _pair - -from ..utils import ext_loader - -ext_module = ext_loader.load_ext( - '_ext', ['dynamic_voxelize_forward', 'hard_voxelize_forward']) - - -class _Voxelization(Function): - - @staticmethod - def forward(ctx, - points, - voxel_size, - coors_range, - max_points=35, - max_voxels=20000): - """Convert kitti points(N, >=3) to voxels. - - Args: - points (torch.Tensor): [N, ndim]. Points[:, :3] contain xyz points - and points[:, 3:] contain other information like reflectivity. - voxel_size (tuple or float): The size of voxel with the shape of - [3]. - coors_range (tuple or float): The coordinate range of voxel with - the shape of [6]. - max_points (int, optional): maximum points contained in a voxel. if - max_points=-1, it means using dynamic_voxelize. Default: 35. - max_voxels (int, optional): maximum voxels this function create. - for second, 20000 is a good choice. Users should shuffle points - before call this function because max_voxels may drop points. - Default: 20000. - - Returns: - voxels_out (torch.Tensor): Output voxels with the shape of [M, - max_points, ndim]. Only contain points and returned when - max_points != -1. - coors_out (torch.Tensor): Output coordinates with the shape of - [M, 3]. - num_points_per_voxel_out (torch.Tensor): Num points per voxel with - the shape of [M]. Only returned when max_points != -1. - """ - if max_points == -1 or max_voxels == -1: - coors = points.new_zeros(size=(points.size(0), 3), dtype=torch.int) - ext_module.dynamic_voxelize_forward(points, coors, voxel_size, - coors_range, 3) - return coors - else: - voxels = points.new_zeros( - size=(max_voxels, max_points, points.size(1))) - coors = points.new_zeros(size=(max_voxels, 3), dtype=torch.int) - num_points_per_voxel = points.new_zeros( - size=(max_voxels, ), dtype=torch.int) - voxel_num = ext_module.hard_voxelize_forward( - points, voxels, coors, num_points_per_voxel, voxel_size, - coors_range, max_points, max_voxels, 3) - # select the valid voxels - voxels_out = voxels[:voxel_num] - coors_out = coors[:voxel_num] - num_points_per_voxel_out = num_points_per_voxel[:voxel_num] - return voxels_out, coors_out, num_points_per_voxel_out - - -voxelization = _Voxelization.apply - - -class Voxelization(nn.Module): - """Convert kitti points(N, >=3) to voxels. - - Please refer to `PVCNN `_ for more - details. - - Args: - voxel_size (tuple or float): The size of voxel with the shape of [3]. - point_cloud_range (tuple or float): The coordinate range of voxel with - the shape of [6]. - max_num_points (int): maximum points contained in a voxel. if - max_points=-1, it means using dynamic_voxelize. - max_voxels (int, optional): maximum voxels this function create. - for second, 20000 is a good choice. Users should shuffle points - before call this function because max_voxels may drop points. - Default: 20000. - """ - - def __init__(self, - voxel_size, - point_cloud_range, - max_num_points, - max_voxels=20000): - super().__init__() - - self.voxel_size = voxel_size - self.point_cloud_range = point_cloud_range - self.max_num_points = max_num_points - if isinstance(max_voxels, tuple): - self.max_voxels = max_voxels - else: - self.max_voxels = _pair(max_voxels) - - point_cloud_range = torch.tensor( - point_cloud_range, dtype=torch.float32) - voxel_size = torch.tensor(voxel_size, dtype=torch.float32) - grid_size = (point_cloud_range[3:] - - point_cloud_range[:3]) / voxel_size - grid_size = torch.round(grid_size).long() - input_feat_shape = grid_size[:2] - self.grid_size = grid_size - # the origin shape is as [x-len, y-len, z-len] - # [w, h, d] -> [d, h, w] - self.pcd_shape = [*input_feat_shape, 1][::-1] - - def forward(self, input): - if self.training: - max_voxels = self.max_voxels[0] - else: - max_voxels = self.max_voxels[1] - - return voxelization(input, self.voxel_size, self.point_cloud_range, - self.max_num_points, max_voxels) - - def __repr__(self): - s = self.__class__.__name__ + '(' - s += 'voxel_size=' + str(self.voxel_size) - s += ', point_cloud_range=' + str(self.point_cloud_range) - s += ', max_num_points=' + str(self.max_num_points) - s += ', max_voxels=' + str(self.max_voxels) - s += ')' - return s diff --git a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/layers/smooth_l1_loss.py b/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/layers/smooth_l1_loss.py deleted file mode 100644 index 9c4664bb47b731eb087aa777d6f9a4b28fddd03a..0000000000000000000000000000000000000000 --- a/spaces/Pinwheel/GLIP-BLIP-Object-Detection-VQA/maskrcnn_benchmark/layers/smooth_l1_loss.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -import torch - - -# TODO maybe push this to nn? -def smooth_l1_loss(input, target, beta=1. / 9, size_average=True): - """ - very similar to the smooth_l1_loss from pytorch, but with - the extra beta parameter - """ - n = torch.abs(input - target) - cond = n < beta - loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta) - if size_average: - return loss.mean() - return loss.sum() diff --git a/spaces/Poupeto/RVC_Ryu7ztv/config.py b/spaces/Poupeto/RVC_Ryu7ztv/config.py deleted file mode 100644 index 040a64d2c5ce4d7802bdf7f69321483b81008f08..0000000000000000000000000000000000000000 --- a/spaces/Poupeto/RVC_Ryu7ztv/config.py +++ /dev/null @@ -1,106 +0,0 @@ -import argparse -import torch -from multiprocessing import cpu_count - -class Config: - def __init__(self): - self.device = "cuda:0" - self.is_half = True - self.n_cpu = 0 - self.gpu_name = None - self.gpu_mem = None - ( - self.python_cmd, - self.listen_port, - self.colab, - self.noparallel, - self.noautoopen, - self.api - ) = self.arg_parse() - self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config() - - @staticmethod - def arg_parse() -> tuple: - parser = argparse.ArgumentParser() - parser.add_argument("--port", type=int, default=7865, help="Listen port") - parser.add_argument( - "--pycmd", type=str, default="python", help="Python command" - ) - parser.add_argument("--colab", action="store_true", help="Launch in colab") - parser.add_argument( - "--noparallel", action="store_true", help="Disable parallel processing" - ) - parser.add_argument( - "--noautoopen", - action="store_true", - help="Do not open in browser automatically", - ) - parser.add_argument("--api", action="store_true", help="Launch with api") - cmd_opts = parser.parse_args() - - cmd_opts.port = cmd_opts.port if 0 <= cmd_opts.port <= 65535 else 7865 - - return ( - cmd_opts.pycmd, - cmd_opts.port, - cmd_opts.colab, - cmd_opts.noparallel, - cmd_opts.noautoopen, - cmd_opts.api - ) - - def device_config(self) -> tuple: - if torch.cuda.is_available(): - i_device = int(self.device.split(":")[-1]) - self.gpu_name = torch.cuda.get_device_name(i_device) - if ( - ("16" in self.gpu_name and "V100" not in self.gpu_name.upper()) - or "P40" in self.gpu_name.upper() - or "1060" in self.gpu_name - or "1070" in self.gpu_name - or "1080" in self.gpu_name - ): - print("16系/10系显卡和P40强制单精度") - self.is_half = False - - else: - self.gpu_name = None - self.gpu_mem = int( - torch.cuda.get_device_properties(i_device).total_memory - / 1024 - / 1024 - / 1024 - + 0.4 - ) - elif torch.backends.mps.is_available(): - print("没有发现支持的N卡, 使用MPS进行推理") - self.device = "mps" - self.is_half = False - else: - print("没有发现支持的N卡, 使用CPU进行推理") - self.device = "cpu" - self.is_half = False - - if self.n_cpu == 0: - self.n_cpu = cpu_count() - - if self.is_half: - # 6G显存配置 - x_pad = 3 - x_query = 10 - x_center = 60 - x_max = 65 - else: - # 5G显存配置 - x_pad = 1 - x_query = 6 - x_center = 38 - x_max = 41 - - if self.gpu_mem != None and self.gpu_mem <= 4: - x_pad = 1 - x_query = 5 - x_center = 30 - x_max = 32 - - return x_pad, x_query, x_center, x_max diff --git a/spaces/RMeli/gnina-torch/app.py b/spaces/RMeli/gnina-torch/app.py deleted file mode 100644 index df49d27401ecc07beaa0813ecb23bfe66722841f..0000000000000000000000000000000000000000 --- a/spaces/RMeli/gnina-torch/app.py +++ /dev/null @@ -1,265 +0,0 @@ -import os - - -def load_file(fpath: str) -> str: - """ - Load file content. - - Parameters - ---------- - fpath: str - File path - - Returns - ------- - str - File content - """ - with open(fpath, "r") as f: - return f.read() - - -def load_html(html_file: str) -> str: - return load_file(os.path.join("html", html_file)) - - -def load_md(md_file: str) -> str: - return load_file(os.path.join("md", md_file)) - - -def load_protein_from_file(protein_file) -> str: - """ - Parameters - ---------- - protein_file: _TemporaryFileWrapper - GradIO file object - - Returns - ------- - str - Protein PDB file content - """ - with open(protein_file.name, "r") as f: - return f.read() - - -def load_ligand_from_file(ligand_file) -> str: - """ - Load ligand from file. - - Parameters - ---------- - ligand_file: _TemporaryFileWrapper - GradIO file object - - Returns - ------- - str - Ligand SDF file content - """ - with open(ligand_file.name, "r") as f: - return f.read() - - -def protein_html_from_file(protein_file) -> str: - """ - Wrap 3Dmol.js code around protein PDB file. - - Parameters - ---------- - protein_file: _TemporaryFileWrapper - GradIO file object - - Returns - ------- - str - 3Dmol.js HTML code for displaying a PDB file - """ - protein = load_protein_from_file(protein_file) - protein_html = load_html("protein.html") - - html = protein_html.replace("%%%PDB%%%", protein) - - wrapper = load_html("wrapper.html") - - return wrapper.replace("%%%HTML%%%", html) - - -def ligand_html_from_file(ligand_file) -> str: - """ - Wrap 3Dmol.js code around ligand SDF file. - - Parameters - ---------- - ligand_file: _TemporaryFileWrapper - GradIO file object - - Returns - ------- - str - 3Dmol.js HTML code for displaying a SDF file - """ - - ligand = load_ligand_from_file(ligand_file) - ligand_html = load_html("ligand.html") - - html = ligand_html.replace("%%%SDF%%%", ligand) - - wrapper = load_html("wrapper.html") - - return wrapper.replace("%%%HTML%%%", html) - - -def protein_ligand_html_from_file(protein_file, ligand_file): - protein = load_protein_from_file(protein_file) - ligand = load_ligand_from_file(ligand_file) - protein_ligand_html = load_html("pl.html") - - html = protein_ligand_html.replace("%%%PDB%%%", protein) - html = html.replace("%%%SDF%%%", ligand) - - wrapper = load_html("wrapper.html") - - return wrapper.replace("%%%HTML%%%", html) - - -def predict(protein_file, ligand_file, cnn: str = "default"): - """ - Run gnina-torch on protein-ligand complex. - - Parameters - ---------- - protein_file: _TemporaryFileWrapper - GradIO file object - ligand_file: _TemporaryFileWrapper - GradIO file object - cnn: str - CNN model to use - - Returns - ------- - dict[str, float] - CNNscore, CNNaffinity, and CNNvariance - """ - import molgrid - from gninatorch import gnina, dataloaders - import torch - import pandas as pd - - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - print(device) - - model, ensemble = gnina.setup_gnina_model(cnn, 23.5, 0.5) - model.eval() - model.to(device) - - example_provider = molgrid.ExampleProvider( - data_root="", - balanced=False, - shuffle=False, - default_batch_size=1, - iteration_scheme=molgrid.IterationScheme.SmallEpoch, - ) - - # FIXME: Do this properly... =( [Might require light gnina-torch refactoring] - with open("data.in", "w") as f: - f.write(protein_file.name) - f.write(" ") - f.write(ligand_file.name) - - print("Populating example provider... ", end="") - example_provider.populate("data.in") - print("done") - - grid_maker = molgrid.GridMaker(resolution=0.5, dimension=23.5) - - # TODO: Allow average over different rotations - loader = dataloaders.GriddedExamplesLoader( - example_provider=example_provider, - grid_maker=grid_maker, - random_translation=0.0, # No random translations for inference - random_rotation=False, # No random rotations for inference - grids_only=True, - device=device, - ) - - print("Loading and gridding data... ", end="") - batch = next(loader) - print("done") - - print("Predicting... ", end="") - with torch.no_grad(): - log_pose, affinity, affinity_var = model(batch) - print("done") - - return pd.DataFrame( - { - "CNNscore": [torch.exp(log_pose[:, -1]).item()], - "CNNaffinity": [affinity.item()], - "CNNvariance": [affinity_var.item()], - } - ).round(6) - - -if __name__ == "__main__": - import gradio as gr - - demo = gr.Blocks() - - with demo: - gr.Markdown(load_md("intro.md")) - - gr.Markdown(load_md("input.md")) - with gr.Row(): - with gr.Box(): - pfile = gr.File(file_count="single", label="Protein file (PDB)") - gr.Examples(["mols/1cbr_protein.pdb"], inputs=pfile) - - pbtn = gr.Button("View Protein") - pbtn.click(fn=protein_html_from_file, inputs=[pfile], outputs=gr.HTML()) - - with gr.Box(): - lfile = gr.File(file_count="single", label="Ligand file (SDF)") - gr.Examples(["mols/1cbr_ligand.sdf"], inputs=lfile) - lbtn = gr.Button("View Ligand") - - lbtn.click(fn=ligand_html_from_file, inputs=[lfile], outputs=gr.HTML()) - - with gr.Box(): - with gr.Column(): - # TODO: Automatically display complex when both files are uploaded - plbtn = gr.Button("View Protein-Ligand Complex") - plbtn.click( - fn=protein_ligand_html_from_file, - inputs=[pfile, lfile], - outputs=gr.HTML(), - ) - - gr.Markdown(load_md("scoring.md")) - - with gr.Row(): - df = gr.Dataframe() - - with gr.Column(): - dd = gr.Dropdown( - choices=[ - "default", - "redock_default2018_ensemble", - "general_default2018_ensemble", - "crossdock_default2018_ensemble", - ], - value="default", - label="CNN model", - ) - - with gr.Row(): - btn = gr.Button("Score!") - btn.click(fn=predict, inputs=[pfile, lfile, dd], outputs=df) - - gr.Markdown( - load_md("acknowledgements.md"), - ) - - gr.Markdown(load_md("references.md")) - - demo.launch() diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_internal/models/candidate.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_internal/models/candidate.py deleted file mode 100644 index a4963aec6388c27c3beb064f0a730af200380aee..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_internal/models/candidate.py +++ /dev/null @@ -1,34 +0,0 @@ -from pip._vendor.packaging.version import parse as parse_version - -from pip._internal.models.link import Link -from pip._internal.utils.models import KeyBasedCompareMixin - - -class InstallationCandidate(KeyBasedCompareMixin): - """Represents a potential "candidate" for installation.""" - - __slots__ = ["name", "version", "link"] - - def __init__(self, name: str, version: str, link: Link) -> None: - self.name = name - self.version = parse_version(version) - self.link = link - - super().__init__( - key=(self.name, self.version, self.link), - defining_class=InstallationCandidate, - ) - - def __repr__(self) -> str: - return "".format( - self.name, - self.version, - self.link, - ) - - def __str__(self) -> str: - return "{!r} candidate (version {} at {})".format( - self.name, - self.version, - self.link, - ) diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/filters/__init__.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/filters/__init__.py deleted file mode 100644 index c302a6c0c53d7efa8767bd55da2a73535bea0cbf..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/pygments/filters/__init__.py +++ /dev/null @@ -1,940 +0,0 @@ -""" - pygments.filters - ~~~~~~~~~~~~~~~~ - - Module containing filter lookup functions and default - filters. - - :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re - -from pip._vendor.pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \ - string_to_tokentype -from pip._vendor.pygments.filter import Filter -from pip._vendor.pygments.util import get_list_opt, get_int_opt, get_bool_opt, \ - get_choice_opt, ClassNotFound, OptionError -from pip._vendor.pygments.plugin import find_plugin_filters - - -def find_filter_class(filtername): - """Lookup a filter by name. Return None if not found.""" - if filtername in FILTERS: - return FILTERS[filtername] - for name, cls in find_plugin_filters(): - if name == filtername: - return cls - return None - - -def get_filter_by_name(filtername, **options): - """Return an instantiated filter. - - Options are passed to the filter initializer if wanted. - Raise a ClassNotFound if not found. - """ - cls = find_filter_class(filtername) - if cls: - return cls(**options) - else: - raise ClassNotFound('filter %r not found' % filtername) - - -def get_all_filters(): - """Return a generator of all filter names.""" - yield from FILTERS - for name, _ in find_plugin_filters(): - yield name - - -def _replace_special(ttype, value, regex, specialttype, - replacefunc=lambda x: x): - last = 0 - for match in regex.finditer(value): - start, end = match.start(), match.end() - if start != last: - yield ttype, value[last:start] - yield specialttype, replacefunc(value[start:end]) - last = end - if last != len(value): - yield ttype, value[last:] - - -class CodeTagFilter(Filter): - """Highlight special code tags in comments and docstrings. - - Options accepted: - - `codetags` : list of strings - A list of strings that are flagged as code tags. The default is to - highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``. - - .. versionchanged:: 2.13 - Now recognizes ``FIXME`` by default. - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - tags = get_list_opt(options, 'codetags', - ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE']) - self.tag_re = re.compile(r'\b(%s)\b' % '|'.join([ - re.escape(tag) for tag in tags if tag - ])) - - def filter(self, lexer, stream): - regex = self.tag_re - for ttype, value in stream: - if ttype in String.Doc or \ - ttype in Comment and \ - ttype not in Comment.Preproc: - yield from _replace_special(ttype, value, regex, Comment.Special) - else: - yield ttype, value - - -class SymbolFilter(Filter): - """Convert mathematical symbols such as \\ in Isabelle - or \\longrightarrow in LaTeX into Unicode characters. - - This is mostly useful for HTML or console output when you want to - approximate the source rendering you'd see in an IDE. - - Options accepted: - - `lang` : string - The symbol language. Must be one of ``'isabelle'`` or - ``'latex'``. The default is ``'isabelle'``. - """ - - latex_symbols = { - '\\alpha' : '\U000003b1', - '\\beta' : '\U000003b2', - '\\gamma' : '\U000003b3', - '\\delta' : '\U000003b4', - '\\varepsilon' : '\U000003b5', - '\\zeta' : '\U000003b6', - '\\eta' : '\U000003b7', - '\\vartheta' : '\U000003b8', - '\\iota' : '\U000003b9', - '\\kappa' : '\U000003ba', - '\\lambda' : '\U000003bb', - '\\mu' : '\U000003bc', - '\\nu' : '\U000003bd', - '\\xi' : '\U000003be', - '\\pi' : '\U000003c0', - '\\varrho' : '\U000003c1', - '\\sigma' : '\U000003c3', - '\\tau' : '\U000003c4', - '\\upsilon' : '\U000003c5', - '\\varphi' : '\U000003c6', - '\\chi' : '\U000003c7', - '\\psi' : '\U000003c8', - '\\omega' : '\U000003c9', - '\\Gamma' : '\U00000393', - '\\Delta' : '\U00000394', - '\\Theta' : '\U00000398', - '\\Lambda' : '\U0000039b', - '\\Xi' : '\U0000039e', - '\\Pi' : '\U000003a0', - '\\Sigma' : '\U000003a3', - '\\Upsilon' : '\U000003a5', - '\\Phi' : '\U000003a6', - '\\Psi' : '\U000003a8', - '\\Omega' : '\U000003a9', - '\\leftarrow' : '\U00002190', - '\\longleftarrow' : '\U000027f5', - '\\rightarrow' : '\U00002192', - '\\longrightarrow' : '\U000027f6', - '\\Leftarrow' : '\U000021d0', - '\\Longleftarrow' : '\U000027f8', - '\\Rightarrow' : '\U000021d2', - '\\Longrightarrow' : '\U000027f9', - '\\leftrightarrow' : '\U00002194', - '\\longleftrightarrow' : '\U000027f7', - '\\Leftrightarrow' : '\U000021d4', - '\\Longleftrightarrow' : '\U000027fa', - '\\mapsto' : '\U000021a6', - '\\longmapsto' : '\U000027fc', - '\\relbar' : '\U00002500', - '\\Relbar' : '\U00002550', - '\\hookleftarrow' : '\U000021a9', - '\\hookrightarrow' : '\U000021aa', - '\\leftharpoondown' : '\U000021bd', - '\\rightharpoondown' : '\U000021c1', - '\\leftharpoonup' : '\U000021bc', - '\\rightharpoonup' : '\U000021c0', - '\\rightleftharpoons' : '\U000021cc', - '\\leadsto' : '\U0000219d', - '\\downharpoonleft' : '\U000021c3', - '\\downharpoonright' : '\U000021c2', - '\\upharpoonleft' : '\U000021bf', - '\\upharpoonright' : '\U000021be', - '\\restriction' : '\U000021be', - '\\uparrow' : '\U00002191', - '\\Uparrow' : '\U000021d1', - '\\downarrow' : '\U00002193', - '\\Downarrow' : '\U000021d3', - '\\updownarrow' : '\U00002195', - '\\Updownarrow' : '\U000021d5', - '\\langle' : '\U000027e8', - '\\rangle' : '\U000027e9', - '\\lceil' : '\U00002308', - '\\rceil' : '\U00002309', - '\\lfloor' : '\U0000230a', - '\\rfloor' : '\U0000230b', - '\\flqq' : '\U000000ab', - '\\frqq' : '\U000000bb', - '\\bot' : '\U000022a5', - '\\top' : '\U000022a4', - '\\wedge' : '\U00002227', - '\\bigwedge' : '\U000022c0', - '\\vee' : '\U00002228', - '\\bigvee' : '\U000022c1', - '\\forall' : '\U00002200', - '\\exists' : '\U00002203', - '\\nexists' : '\U00002204', - '\\neg' : '\U000000ac', - '\\Box' : '\U000025a1', - '\\Diamond' : '\U000025c7', - '\\vdash' : '\U000022a2', - '\\models' : '\U000022a8', - '\\dashv' : '\U000022a3', - '\\surd' : '\U0000221a', - '\\le' : '\U00002264', - '\\ge' : '\U00002265', - '\\ll' : '\U0000226a', - '\\gg' : '\U0000226b', - '\\lesssim' : '\U00002272', - '\\gtrsim' : '\U00002273', - '\\lessapprox' : '\U00002a85', - '\\gtrapprox' : '\U00002a86', - '\\in' : '\U00002208', - '\\notin' : '\U00002209', - '\\subset' : '\U00002282', - '\\supset' : '\U00002283', - '\\subseteq' : '\U00002286', - '\\supseteq' : '\U00002287', - '\\sqsubset' : '\U0000228f', - '\\sqsupset' : '\U00002290', - '\\sqsubseteq' : '\U00002291', - '\\sqsupseteq' : '\U00002292', - '\\cap' : '\U00002229', - '\\bigcap' : '\U000022c2', - '\\cup' : '\U0000222a', - '\\bigcup' : '\U000022c3', - '\\sqcup' : '\U00002294', - '\\bigsqcup' : '\U00002a06', - '\\sqcap' : '\U00002293', - '\\Bigsqcap' : '\U00002a05', - '\\setminus' : '\U00002216', - '\\propto' : '\U0000221d', - '\\uplus' : '\U0000228e', - '\\bigplus' : '\U00002a04', - '\\sim' : '\U0000223c', - '\\doteq' : '\U00002250', - '\\simeq' : '\U00002243', - '\\approx' : '\U00002248', - '\\asymp' : '\U0000224d', - '\\cong' : '\U00002245', - '\\equiv' : '\U00002261', - '\\Join' : '\U000022c8', - '\\bowtie' : '\U00002a1d', - '\\prec' : '\U0000227a', - '\\succ' : '\U0000227b', - '\\preceq' : '\U0000227c', - '\\succeq' : '\U0000227d', - '\\parallel' : '\U00002225', - '\\mid' : '\U000000a6', - '\\pm' : '\U000000b1', - '\\mp' : '\U00002213', - '\\times' : '\U000000d7', - '\\div' : '\U000000f7', - '\\cdot' : '\U000022c5', - '\\star' : '\U000022c6', - '\\circ' : '\U00002218', - '\\dagger' : '\U00002020', - '\\ddagger' : '\U00002021', - '\\lhd' : '\U000022b2', - '\\rhd' : '\U000022b3', - '\\unlhd' : '\U000022b4', - '\\unrhd' : '\U000022b5', - '\\triangleleft' : '\U000025c3', - '\\triangleright' : '\U000025b9', - '\\triangle' : '\U000025b3', - '\\triangleq' : '\U0000225c', - '\\oplus' : '\U00002295', - '\\bigoplus' : '\U00002a01', - '\\otimes' : '\U00002297', - '\\bigotimes' : '\U00002a02', - '\\odot' : '\U00002299', - '\\bigodot' : '\U00002a00', - '\\ominus' : '\U00002296', - '\\oslash' : '\U00002298', - '\\dots' : '\U00002026', - '\\cdots' : '\U000022ef', - '\\sum' : '\U00002211', - '\\prod' : '\U0000220f', - '\\coprod' : '\U00002210', - '\\infty' : '\U0000221e', - '\\int' : '\U0000222b', - '\\oint' : '\U0000222e', - '\\clubsuit' : '\U00002663', - '\\diamondsuit' : '\U00002662', - '\\heartsuit' : '\U00002661', - '\\spadesuit' : '\U00002660', - '\\aleph' : '\U00002135', - '\\emptyset' : '\U00002205', - '\\nabla' : '\U00002207', - '\\partial' : '\U00002202', - '\\flat' : '\U0000266d', - '\\natural' : '\U0000266e', - '\\sharp' : '\U0000266f', - '\\angle' : '\U00002220', - '\\copyright' : '\U000000a9', - '\\textregistered' : '\U000000ae', - '\\textonequarter' : '\U000000bc', - '\\textonehalf' : '\U000000bd', - '\\textthreequarters' : '\U000000be', - '\\textordfeminine' : '\U000000aa', - '\\textordmasculine' : '\U000000ba', - '\\euro' : '\U000020ac', - '\\pounds' : '\U000000a3', - '\\yen' : '\U000000a5', - '\\textcent' : '\U000000a2', - '\\textcurrency' : '\U000000a4', - '\\textdegree' : '\U000000b0', - } - - isabelle_symbols = { - '\\' : '\U0001d7ec', - '\\' : '\U0001d7ed', - '\\' : '\U0001d7ee', - '\\' : '\U0001d7ef', - '\\' : '\U0001d7f0', - '\\' : '\U0001d7f1', - '\\' : '\U0001d7f2', - '\\' : '\U0001d7f3', - '\\' : '\U0001d7f4', - '\\' : '\U0001d7f5', - '\\' : '\U0001d49c', - '\\' : '\U0000212c', - '\\' : '\U0001d49e', - '\\' : '\U0001d49f', - '\\' : '\U00002130', - '\\' : '\U00002131', - '\\' : '\U0001d4a2', - '\\' : '\U0000210b', - '\\' : '\U00002110', - '\\' : '\U0001d4a5', - '\\' : '\U0001d4a6', - '\\' : '\U00002112', - '\\' : '\U00002133', - '\\' : '\U0001d4a9', - '\\' : '\U0001d4aa', - '\\

' : '\U0001d5c9', - '\\' : '\U0001d5ca', - '\\' : '\U0001d5cb', - '\\' : '\U0001d5cc', - '\\' : '\U0001d5cd', - '\\' : '\U0001d5ce', - '\\' : '\U0001d5cf', - '\\' : '\U0001d5d0', - '\\' : '\U0001d5d1', - '\\' : '\U0001d5d2', - '\\' : '\U0001d5d3', - '\\' : '\U0001d504', - '\\' : '\U0001d505', - '\\' : '\U0000212d', - '\\

' : '\U0001d507', - '\\' : '\U0001d508', - '\\' : '\U0001d509', - '\\' : '\U0001d50a', - '\\' : '\U0000210c', - '\\' : '\U00002111', - '\\' : '\U0001d50d', - '\\' : '\U0001d50e', - '\\' : '\U0001d50f', - '\\' : '\U0001d510', - '\\' : '\U0001d511', - '\\' : '\U0001d512', - '\\' : '\U0001d513', - '\\' : '\U0001d514', - '\\' : '\U0000211c', - '\\' : '\U0001d516', - '\\' : '\U0001d517', - '\\' : '\U0001d518', - '\\' : '\U0001d519', - '\\' : '\U0001d51a', - '\\' : '\U0001d51b', - '\\' : '\U0001d51c', - '\\' : '\U00002128', - '\\' : '\U0001d51e', - '\\' : '\U0001d51f', - '\\' : '\U0001d520', - '\\
' : '\U0001d521', - '\\' : '\U0001d522', - '\\' : '\U0001d523', - '\\' : '\U0001d524', - '\\' : '\U0001d525', - '\\' : '\U0001d526', - '\\' : '\U0001d527', - '\\' : '\U0001d528', - '\\' : '\U0001d529', - '\\' : '\U0001d52a', - '\\' : '\U0001d52b', - '\\' : '\U0001d52c', - '\\' : '\U0001d52d', - '\\' : '\U0001d52e', - '\\' : '\U0001d52f', - '\\' : '\U0001d530', - '\\' : '\U0001d531', - '\\' : '\U0001d532', - '\\' : '\U0001d533', - '\\' : '\U0001d534', - '\\' : '\U0001d535', - '\\' : '\U0001d536', - '\\' : '\U0001d537', - '\\' : '\U000003b1', - '\\' : '\U000003b2', - '\\' : '\U000003b3', - '\\' : '\U000003b4', - '\\' : '\U000003b5', - '\\' : '\U000003b6', - '\\' : '\U000003b7', - '\\' : '\U000003b8', - '\\' : '\U000003b9', - '\\' : '\U000003ba', - '\\' : '\U000003bb', - '\\' : '\U000003bc', - '\\' : '\U000003bd', - '\\' : '\U000003be', - '\\' : '\U000003c0', - '\\' : '\U000003c1', - '\\' : '\U000003c3', - '\\' : '\U000003c4', - '\\' : '\U000003c5', - '\\' : '\U000003c6', - '\\' : '\U000003c7', - '\\' : '\U000003c8', - '\\' : '\U000003c9', - '\\' : '\U00000393', - '\\' : '\U00000394', - '\\' : '\U00000398', - '\\' : '\U0000039b', - '\\' : '\U0000039e', - '\\' : '\U000003a0', - '\\' : '\U000003a3', - '\\' : '\U000003a5', - '\\' : '\U000003a6', - '\\' : '\U000003a8', - '\\' : '\U000003a9', - '\\' : '\U0001d539', - '\\' : '\U00002102', - '\\' : '\U00002115', - '\\' : '\U0000211a', - '\\' : '\U0000211d', - '\\' : '\U00002124', - '\\' : '\U00002190', - '\\' : '\U000027f5', - '\\' : '\U00002192', - '\\' : '\U000027f6', - '\\' : '\U000021d0', - '\\' : '\U000027f8', - '\\' : '\U000021d2', - '\\' : '\U000027f9', - '\\' : '\U00002194', - '\\' : '\U000027f7', - '\\' : '\U000021d4', - '\\' : '\U000027fa', - '\\' : '\U000021a6', - '\\' : '\U000027fc', - '\\' : '\U00002500', - '\\' : '\U00002550', - '\\' : '\U000021a9', - '\\' : '\U000021aa', - '\\' : '\U000021bd', - '\\' : '\U000021c1', - '\\' : '\U000021bc', - '\\' : '\U000021c0', - '\\' : '\U000021cc', - '\\' : '\U0000219d', - '\\' : '\U000021c3', - '\\' : '\U000021c2', - '\\' : '\U000021bf', - '\\' : '\U000021be', - '\\' : '\U000021be', - '\\' : '\U00002237', - '\\' : '\U00002191', - '\\' : '\U000021d1', - '\\' : '\U00002193', - '\\' : '\U000021d3', - '\\' : '\U00002195', - '\\' : '\U000021d5', - '\\' : '\U000027e8', - '\\' : '\U000027e9', - '\\' : '\U00002308', - '\\' : '\U00002309', - '\\' : '\U0000230a', - '\\' : '\U0000230b', - '\\' : '\U00002987', - '\\' : '\U00002988', - '\\' : '\U000027e6', - '\\' : '\U000027e7', - '\\' : '\U00002983', - '\\' : '\U00002984', - '\\' : '\U000000ab', - '\\' : '\U000000bb', - '\\' : '\U000022a5', - '\\' : '\U000022a4', - '\\' : '\U00002227', - '\\' : '\U000022c0', - '\\' : '\U00002228', - '\\' : '\U000022c1', - '\\' : '\U00002200', - '\\' : '\U00002203', - '\\' : '\U00002204', - '\\' : '\U000000ac', - '\\' : '\U000025a1', - '\\' : '\U000025c7', - '\\' : '\U000022a2', - '\\' : '\U000022a8', - '\\' : '\U000022a9', - '\\' : '\U000022ab', - '\\' : '\U000022a3', - '\\' : '\U0000221a', - '\\' : '\U00002264', - '\\' : '\U00002265', - '\\' : '\U0000226a', - '\\' : '\U0000226b', - '\\' : '\U00002272', - '\\' : '\U00002273', - '\\' : '\U00002a85', - '\\' : '\U00002a86', - '\\' : '\U00002208', - '\\' : '\U00002209', - '\\' : '\U00002282', - '\\' : '\U00002283', - '\\' : '\U00002286', - '\\' : '\U00002287', - '\\' : '\U0000228f', - '\\' : '\U00002290', - '\\' : '\U00002291', - '\\' : '\U00002292', - '\\' : '\U00002229', - '\\' : '\U000022c2', - '\\' : '\U0000222a', - '\\' : '\U000022c3', - '\\' : '\U00002294', - '\\' : '\U00002a06', - '\\' : '\U00002293', - '\\' : '\U00002a05', - '\\' : '\U00002216', - '\\' : '\U0000221d', - '\\' : '\U0000228e', - '\\' : '\U00002a04', - '\\' : '\U00002260', - '\\' : '\U0000223c', - '\\' : '\U00002250', - '\\' : '\U00002243', - '\\' : '\U00002248', - '\\' : '\U0000224d', - '\\' : '\U00002245', - '\\' : '\U00002323', - '\\' : '\U00002261', - '\\' : '\U00002322', - '\\' : '\U000022c8', - '\\' : '\U00002a1d', - '\\' : '\U0000227a', - '\\' : '\U0000227b', - '\\' : '\U0000227c', - '\\' : '\U0000227d', - '\\' : '\U00002225', - '\\' : '\U000000a6', - '\\' : '\U000000b1', - '\\' : '\U00002213', - '\\' : '\U000000d7', - '\\
' : '\U000000f7', - '\\' : '\U000022c5', - '\\' : '\U000022c6', - '\\' : '\U00002219', - '\\' : '\U00002218', - '\\' : '\U00002020', - '\\' : '\U00002021', - '\\' : '\U000022b2', - '\\' : '\U000022b3', - '\\' : '\U000022b4', - '\\' : '\U000022b5', - '\\' : '\U000025c3', - '\\' : '\U000025b9', - '\\' : '\U000025b3', - '\\' : '\U0000225c', - '\\' : '\U00002295', - '\\' : '\U00002a01', - '\\' : '\U00002297', - '\\' : '\U00002a02', - '\\' : '\U00002299', - '\\' : '\U00002a00', - '\\' : '\U00002296', - '\\' : '\U00002298', - '\\' : '\U00002026', - '\\' : '\U000022ef', - '\\' : '\U00002211', - '\\' : '\U0000220f', - '\\' : '\U00002210', - '\\' : '\U0000221e', - '\\' : '\U0000222b', - '\\' : '\U0000222e', - '\\' : '\U00002663', - '\\' : '\U00002662', - '\\' : '\U00002661', - '\\' : '\U00002660', - '\\' : '\U00002135', - '\\' : '\U00002205', - '\\' : '\U00002207', - '\\' : '\U00002202', - '\\' : '\U0000266d', - '\\' : '\U0000266e', - '\\' : '\U0000266f', - '\\' : '\U00002220', - '\\' : '\U000000a9', - '\\' : '\U000000ae', - '\\' : '\U000000ad', - '\\' : '\U000000af', - '\\' : '\U000000bc', - '\\' : '\U000000bd', - '\\' : '\U000000be', - '\\' : '\U000000aa', - '\\' : '\U000000ba', - '\\
' : '\U000000a7', - '\\' : '\U000000b6', - '\\' : '\U000000a1', - '\\' : '\U000000bf', - '\\' : '\U000020ac', - '\\' : '\U000000a3', - '\\' : '\U000000a5', - '\\' : '\U000000a2', - '\\' : '\U000000a4', - '\\' : '\U000000b0', - '\\' : '\U00002a3f', - '\\' : '\U00002127', - '\\' : '\U000025ca', - '\\' : '\U00002118', - '\\' : '\U00002240', - '\\' : '\U000022c4', - '\\' : '\U000000b4', - '\\' : '\U00000131', - '\\' : '\U000000a8', - '\\' : '\U000000b8', - '\\' : '\U000002dd', - '\\' : '\U000003f5', - '\\' : '\U000023ce', - '\\' : '\U00002039', - '\\' : '\U0000203a', - '\\' : '\U00002302', - '\\<^sub>' : '\U000021e9', - '\\<^sup>' : '\U000021e7', - '\\<^bold>' : '\U00002759', - '\\<^bsub>' : '\U000021d8', - '\\<^esub>' : '\U000021d9', - '\\<^bsup>' : '\U000021d7', - '\\<^esup>' : '\U000021d6', - } - - lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols} - - def __init__(self, **options): - Filter.__init__(self, **options) - lang = get_choice_opt(options, 'lang', - ['isabelle', 'latex'], 'isabelle') - self.symbols = self.lang_map[lang] - - def filter(self, lexer, stream): - for ttype, value in stream: - if value in self.symbols: - yield ttype, self.symbols[value] - else: - yield ttype, value - - -class KeywordCaseFilter(Filter): - """Convert keywords to lowercase or uppercase or capitalize them, which - means first letter uppercase, rest lowercase. - - This can be useful e.g. if you highlight Pascal code and want to adapt the - code to your styleguide. - - Options accepted: - - `case` : string - The casing to convert keywords to. Must be one of ``'lower'``, - ``'upper'`` or ``'capitalize'``. The default is ``'lower'``. - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - case = get_choice_opt(options, 'case', - ['lower', 'upper', 'capitalize'], 'lower') - self.convert = getattr(str, case) - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype in Keyword: - yield ttype, self.convert(value) - else: - yield ttype, value - - -class NameHighlightFilter(Filter): - """Highlight a normal Name (and Name.*) token with a different token type. - - Example:: - - filter = NameHighlightFilter( - names=['foo', 'bar', 'baz'], - tokentype=Name.Function, - ) - - This would highlight the names "foo", "bar" and "baz" - as functions. `Name.Function` is the default token type. - - Options accepted: - - `names` : list of strings - A list of names that should be given the different token type. - There is no default. - `tokentype` : TokenType or string - A token type or a string containing a token type name that is - used for highlighting the strings in `names`. The default is - `Name.Function`. - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - self.names = set(get_list_opt(options, 'names', [])) - tokentype = options.get('tokentype') - if tokentype: - self.tokentype = string_to_tokentype(tokentype) - else: - self.tokentype = Name.Function - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype in Name and value in self.names: - yield self.tokentype, value - else: - yield ttype, value - - -class ErrorToken(Exception): - pass - - -class RaiseOnErrorTokenFilter(Filter): - """Raise an exception when the lexer generates an error token. - - Options accepted: - - `excclass` : Exception class - The exception class to raise. - The default is `pygments.filters.ErrorToken`. - - .. versionadded:: 0.8 - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - self.exception = options.get('excclass', ErrorToken) - try: - # issubclass() will raise TypeError if first argument is not a class - if not issubclass(self.exception, Exception): - raise TypeError - except TypeError: - raise OptionError('excclass option is not an exception class') - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype is Error: - raise self.exception(value) - yield ttype, value - - -class VisibleWhitespaceFilter(Filter): - """Convert tabs, newlines and/or spaces to visible characters. - - Options accepted: - - `spaces` : string or bool - If this is a one-character string, spaces will be replaces by this string. - If it is another true value, spaces will be replaced by ``·`` (unicode - MIDDLE DOT). If it is a false value, spaces will not be replaced. The - default is ``False``. - `tabs` : string or bool - The same as for `spaces`, but the default replacement character is ``»`` - (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value - is ``False``. Note: this will not work if the `tabsize` option for the - lexer is nonzero, as tabs will already have been expanded then. - `tabsize` : int - If tabs are to be replaced by this filter (see the `tabs` option), this - is the total number of characters that a tab should be expanded to. - The default is ``8``. - `newlines` : string or bool - The same as for `spaces`, but the default replacement character is ``¶`` - (unicode PILCROW SIGN). The default value is ``False``. - `wstokentype` : bool - If true, give whitespace the special `Whitespace` token type. This allows - styling the visible whitespace differently (e.g. greyed out), but it can - disrupt background colors. The default is ``True``. - - .. versionadded:: 0.8 - """ - - def __init__(self, **options): - Filter.__init__(self, **options) - for name, default in [('spaces', '·'), - ('tabs', '»'), - ('newlines', '¶')]: - opt = options.get(name, False) - if isinstance(opt, str) and len(opt) == 1: - setattr(self, name, opt) - else: - setattr(self, name, (opt and default or '')) - tabsize = get_int_opt(options, 'tabsize', 8) - if self.tabs: - self.tabs += ' ' * (tabsize - 1) - if self.newlines: - self.newlines += '\n' - self.wstt = get_bool_opt(options, 'wstokentype', True) - - def filter(self, lexer, stream): - if self.wstt: - spaces = self.spaces or ' ' - tabs = self.tabs or '\t' - newlines = self.newlines or '\n' - regex = re.compile(r'\s') - - def replacefunc(wschar): - if wschar == ' ': - return spaces - elif wschar == '\t': - return tabs - elif wschar == '\n': - return newlines - return wschar - - for ttype, value in stream: - yield from _replace_special(ttype, value, regex, Whitespace, - replacefunc) - else: - spaces, tabs, newlines = self.spaces, self.tabs, self.newlines - # simpler processing - for ttype, value in stream: - if spaces: - value = value.replace(' ', spaces) - if tabs: - value = value.replace('\t', tabs) - if newlines: - value = value.replace('\n', newlines) - yield ttype, value - - -class GobbleFilter(Filter): - """Gobbles source code lines (eats initial characters). - - This filter drops the first ``n`` characters off every line of code. This - may be useful when the source code fed to the lexer is indented by a fixed - amount of space that isn't desired in the output. - - Options accepted: - - `n` : int - The number of characters to gobble. - - .. versionadded:: 1.2 - """ - def __init__(self, **options): - Filter.__init__(self, **options) - self.n = get_int_opt(options, 'n', 0) - - def gobble(self, value, left): - if left < len(value): - return value[left:], 0 - else: - return '', left - len(value) - - def filter(self, lexer, stream): - n = self.n - left = n # How many characters left to gobble. - for ttype, value in stream: - # Remove ``left`` tokens from first line, ``n`` from all others. - parts = value.split('\n') - (parts[0], left) = self.gobble(parts[0], left) - for i in range(1, len(parts)): - (parts[i], left) = self.gobble(parts[i], n) - value = '\n'.join(parts) - - if value != '': - yield ttype, value - - -class TokenMergeFilter(Filter): - """Merges consecutive tokens with the same token type in the output - stream of a lexer. - - .. versionadded:: 1.2 - """ - def __init__(self, **options): - Filter.__init__(self, **options) - - def filter(self, lexer, stream): - current_type = None - current_value = None - for ttype, value in stream: - if ttype is current_type: - current_value += value - else: - if current_type is not None: - yield current_type, current_value - current_type = ttype - current_value = value - if current_type is not None: - yield current_type, current_value - - -FILTERS = { - 'codetagify': CodeTagFilter, - 'keywordcase': KeywordCaseFilter, - 'highlight': NameHighlightFilter, - 'raiseonerror': RaiseOnErrorTokenFilter, - 'whitespace': VisibleWhitespaceFilter, - 'gobble': GobbleFilter, - 'tokenmerge': TokenMergeFilter, - 'symbols': SymbolFilter, -} diff --git a/spaces/Realcat/image-matching-webui/hloc/pipelines/4Seasons/README.md b/spaces/Realcat/image-matching-webui/hloc/pipelines/4Seasons/README.md deleted file mode 100644 index ad23ac8348ae9f0963611bc9a342240d5ae97255..0000000000000000000000000000000000000000 --- a/spaces/Realcat/image-matching-webui/hloc/pipelines/4Seasons/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# 4Seasons dataset - -This pipeline localizes sequences from the [4Seasons dataset](https://arxiv.org/abs/2009.06364) and can reproduce our winning submission to the challenge of the [ECCV 2020 Workshop on Map-based Localization for Autonomous Driving](https://sites.google.com/view/mlad-eccv2020/home). - -## Installation - -Download the sequences from the [challenge webpage](https://sites.google.com/view/mlad-eccv2020/challenge) and run: -```bash -unzip recording_2020-04-07_10-20-32.zip -d datasets/4Seasons/reference -unzip recording_2020-03-24_17-36-22.zip -d datasets/4Seasons/training -unzip recording_2020-03-03_12-03-23.zip -d datasets/4Seasons/validation -unzip recording_2020-03-24_17-45-31.zip -d datasets/4Seasons/test0 -unzip recording_2020-04-23_19-37-00.zip -d datasets/4Seasons/test1 -``` -Note that the provided scripts might modify the dataset files by deleting unused images to speed up the feature extraction - -## Pipeline - -The process is presented in our workshop talk, whose recording can be found [here](https://youtu.be/M-X6HX1JxYk?t=5245). - -We first triangulate a 3D model from the given poses of the reference sequence: -```bash -python3 -m hloc.pipelines.4Seasons.prepare_reference -``` - -We then relocalize a given sequence: -```bash -python3 -m hloc.pipelines.4Seasons.localize --sequence [training|validation|test0|test1] -``` - -The final submission files can be found in `outputs/4Seasons/submission_hloc+superglue/`. The script will also evaluate these results if the training or validation sequences are selected. - -## Results - -We evaluate the localization recall at distance thresholds 0.1m, 0.2m, and 0.5m. - -| Methods | test0 | test1 | -| -------------------- | ---------------------- | ---------------------- | -| **hloc + SuperGlue** | **91.8 / 97.7 / 99.2** | **67.3 / 93.5 / 98.7** | -| Baseline SuperGlue | 21.2 / 33.9 / 60.0 | 12.4 / 26.5 / 54.4 | -| Baseline R2D2 | 21.5 / 33.1 / 53.0 | 12.3 / 23.7 / 42.0 | -| Baseline D2Net | 12.5 / 29.3 / 56.7 | 7.5 / 21.4 / 47.7 | -| Baseline SuperPoint | 15.5 / 27.5 / 47.5 | 9.0 / 19.4 / 36.4 | diff --git a/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/dataset/dataset_util.py b/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/dataset/dataset_util.py deleted file mode 100644 index 67271bc915e6975cad005e9001d2bb430a8baa14..0000000000000000000000000000000000000000 --- a/spaces/Realcat/image-matching-webui/third_party/SOLD2/sold2/dataset/dataset_util.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -The interface of initializing different datasets. -""" -from .synthetic_dataset import SyntheticShapes -from .wireframe_dataset import WireframeDataset -from .holicity_dataset import HolicityDataset -from .merge_dataset import MergeDataset - - -def get_dataset(mode="train", dataset_cfg=None): - """Initialize different dataset based on a configuration.""" - # Check dataset config is given - if dataset_cfg is None: - raise ValueError("[Error] The dataset config is required!") - - # Synthetic dataset - if dataset_cfg["dataset_name"] == "synthetic_shape": - dataset = SyntheticShapes(mode, dataset_cfg) - - # Get the collate_fn - from .synthetic_dataset import synthetic_collate_fn - - collate_fn = synthetic_collate_fn - - # Wireframe dataset - elif dataset_cfg["dataset_name"] == "wireframe": - dataset = WireframeDataset(mode, dataset_cfg) - - # Get the collate_fn - from .wireframe_dataset import wireframe_collate_fn - - collate_fn = wireframe_collate_fn - - # Holicity dataset - elif dataset_cfg["dataset_name"] == "holicity": - dataset = HolicityDataset(mode, dataset_cfg) - - # Get the collate_fn - from .holicity_dataset import holicity_collate_fn - - collate_fn = holicity_collate_fn - - # Dataset merging several datasets in one - elif dataset_cfg["dataset_name"] == "merge": - dataset = MergeDataset(mode, dataset_cfg) - - # Get the collate_fn - from .holicity_dataset import holicity_collate_fn - - collate_fn = holicity_collate_fn - - else: - raise ValueError( - "[Error] The dataset '%s' is not supported" % dataset_cfg["dataset_name"] - ) - - return dataset, collate_fn diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/bbox/iou_calculators/__init__.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/bbox/iou_calculators/__init__.py deleted file mode 100644 index e71369a58a05fa25e6a754300875fdbb87cb26a5..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/core/bbox/iou_calculators/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .builder import build_iou_calculator -from .iou2d_calculator import BboxOverlaps2D, bbox_overlaps - -__all__ = ['build_iou_calculator', 'BboxOverlaps2D', 'bbox_overlaps'] diff --git a/spaces/Rothfeld/stable-diffusion-mat-outpainting-primer/evaluatoin/cal_psnr_ssim_l1.py b/spaces/Rothfeld/stable-diffusion-mat-outpainting-primer/evaluatoin/cal_psnr_ssim_l1.py deleted file mode 100644 index 2dbd401e9ccd87b06a1549aaf9656f6b64756d79..0000000000000000000000000000000000000000 --- a/spaces/Rothfeld/stable-diffusion-mat-outpainting-primer/evaluatoin/cal_psnr_ssim_l1.py +++ /dev/null @@ -1,107 +0,0 @@ -import cv2 -import os -import sys -import numpy as np -import math -import glob -import pyspng -import PIL.Image - - -def calculate_psnr(img1, img2): - # img1 and img2 have range [0, 255] - img1 = img1.astype(np.float64) - img2 = img2.astype(np.float64) - mse = np.mean((img1 - img2) ** 2) - if mse == 0: - return float('inf') - - return 20 * math.log10(255.0 / math.sqrt(mse)) - - -def calculate_ssim(img1, img2): - C1 = (0.01 * 255) ** 2 - C2 = (0.03 * 255) ** 2 - - img1 = img1.astype(np.float64) - img2 = img2.astype(np.float64) - kernel = cv2.getGaussianKernel(11, 1.5) - window = np.outer(kernel, kernel.transpose()) - - mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] - mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] - mu1_sq = mu1 ** 2 - mu2_sq = mu2 ** 2 - mu1_mu2 = mu1 * mu2 - sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq - sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq - sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 - - ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) - - return ssim_map.mean() - - -def calculate_l1(img1, img2): - img1 = img1.astype(np.float64) / 255.0 - img2 = img2.astype(np.float64) / 255.0 - l1 = np.mean(np.abs(img1 - img2)) - - return l1 - - -def read_image(image_path): - with open(image_path, 'rb') as f: - if pyspng is not None and image_path.endswith('.png'): - image = pyspng.load(f.read()) - else: - image = np.array(PIL.Image.open(f)) - if image.ndim == 2: - image = image[:, :, np.newaxis] # HW => HWC - if image.shape[2] == 1: - image = np.repeat(image, 3, axis=2) - # image = image.transpose(2, 0, 1) # HWC => CHW - - return image - - -def calculate_metrics(folder1, folder2): - l1 = sorted(glob.glob(folder1 + '/*.png') + glob.glob(folder1 + '/*.jpg')) - l2 = sorted(glob.glob(folder2 + '/*.png') + glob.glob(folder2 + '/*.jpg')) - assert(len(l1) == len(l2)) - print('length:', len(l1)) - - # l1 = l1[:3]; l2 = l2[:3]; - - psnr_l, ssim_l, dl1_l = [], [], [] - for i, (fpath1, fpath2) in enumerate(zip(l1, l2)): - print(i) - _, name1 = os.path.split(fpath1) - _, name2 = os.path.split(fpath2) - name1 = name1.split('.')[0] - name2 = name2.split('.')[0] - assert name1 == name2, 'Illegal mapping: %s, %s' % (name1, name2) - - img1 = read_image(fpath1).astype(np.float64) - img2 = read_image(fpath2).astype(np.float64) - assert img1.shape == img2.shape, 'Illegal shape' - psnr_l.append(calculate_psnr(img1, img2)) - ssim_l.append(calculate_ssim(img1, img2)) - dl1_l.append(calculate_l1(img1, img2)) - - psnr = sum(psnr_l) / len(psnr_l) - ssim = sum(ssim_l) / len(ssim_l) - dl1 = sum(dl1_l) / len(dl1_l) - - return psnr, ssim, dl1 - - -if __name__ == '__main__': - folder1 = 'path to the inpainted result' - folder2 = 'path to the gt' - - psnr, ssim, dl1 = calculate_metrics(folder1, folder2) - print('psnr: %.4f, ssim: %.4f, l1: %.4f' % (psnr, ssim, dl1)) - with open('psnr_ssim_l1.txt', 'w') as f: - f.write('psnr: %.4f, ssim: %.4f, l1: %.4f' % (psnr, ssim, dl1)) - diff --git a/spaces/SShaik/SS-02-H5-AR-VR-IOT/style.css b/spaces/SShaik/SS-02-H5-AR-VR-IOT/style.css deleted file mode 100644 index 114adf441e9032febb46bc056b2a8bb651075f0d..0000000000000000000000000000000000000000 --- a/spaces/SShaik/SS-02-H5-AR-VR-IOT/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/Sapphire-356/Video2MC/README.md b/spaces/Sapphire-356/Video2MC/README.md deleted file mode 100644 index fbd685955782e060c00575e0e18a7015cc9c77d5..0000000000000000000000000000000000000000 --- a/spaces/Sapphire-356/Video2MC/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Video2MC -emoji: 📈 -colorFrom: purple -colorTo: green -sdk: gradio -sdk_version: 3.41.2 -app_file: app.py -pinned: false -license: gpl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/SeViLA/SeViLA/lavis/models/blip2_models/Qformer.py b/spaces/SeViLA/SeViLA/lavis/models/blip2_models/Qformer.py deleted file mode 100644 index e71b12375e10511858a9c505dc795181e6ce5603..0000000000000000000000000000000000000000 --- a/spaces/SeViLA/SeViLA/lavis/models/blip2_models/Qformer.py +++ /dev/null @@ -1,1216 +0,0 @@ -""" - * Copyright (c) 2023, salesforce.com, inc. - * All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - * By Junnan Li - * Based on huggingface code base - * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert -""" - -import math -import os -import warnings -from dataclasses import dataclass -from typing import Optional, Tuple, Dict, Any - -import torch -from torch import Tensor, device, dtype, nn -import torch.utils.checkpoint -from torch import nn -from torch.nn import CrossEntropyLoss -import torch.nn.functional as F - -from transformers.activations import ACT2FN -from transformers.file_utils import ( - ModelOutput, -) -from transformers.modeling_outputs import ( - BaseModelOutputWithPastAndCrossAttentions, - BaseModelOutputWithPoolingAndCrossAttentions, - CausalLMOutputWithCrossAttentions, - MaskedLMOutput, - MultipleChoiceModelOutput, - NextSentencePredictorOutput, - QuestionAnsweringModelOutput, - SequenceClassifierOutput, - TokenClassifierOutput, -) -from transformers.modeling_utils import ( - PreTrainedModel, - apply_chunking_to_forward, - find_pruneable_heads_and_indices, - prune_linear_layer, -) -from transformers.utils import logging -from transformers.models.bert.configuration_bert import BertConfig - -logger = logging.get_logger(__name__) - - -class BertEmbeddings(nn.Module): - """Construct the embeddings from word and position embeddings.""" - - def __init__(self, config): - super().__init__() - self.word_embeddings = nn.Embedding( - config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id - ) - self.position_embeddings = nn.Embedding( - config.max_position_embeddings, config.hidden_size - ) - - # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load - # any TensorFlow checkpoint file - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.hidden_dropout_prob) - - # position_ids (1, len position emb) is contiguous in memory and exported when serialized - self.register_buffer( - "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) - ) - self.position_embedding_type = getattr( - config, "position_embedding_type", "absolute" - ) - - self.config = config - - def forward( - self, - input_ids=None, - position_ids=None, - query_embeds=None, - past_key_values_length=0, - ): - if input_ids is not None: - seq_length = input_ids.size()[1] - else: - seq_length = 0 - - if position_ids is None: - position_ids = self.position_ids[ - :, past_key_values_length : seq_length + past_key_values_length - ].clone() - - if input_ids is not None: - embeddings = self.word_embeddings(input_ids) - if self.position_embedding_type == "absolute": - position_embeddings = self.position_embeddings(position_ids) - embeddings = embeddings + position_embeddings - - if query_embeds is not None: - embeddings = torch.cat((query_embeds, embeddings), dim=1) - else: - embeddings = query_embeds - - embeddings = self.LayerNorm(embeddings) - embeddings = self.dropout(embeddings) - return embeddings - - -class BertSelfAttention(nn.Module): - def __init__(self, config, is_cross_attention): - super().__init__() - self.config = config - if config.hidden_size % config.num_attention_heads != 0 and not hasattr( - config, "embedding_size" - ): - raise ValueError( - "The hidden size (%d) is not a multiple of the number of attention " - "heads (%d)" % (config.hidden_size, config.num_attention_heads) - ) - - self.num_attention_heads = config.num_attention_heads - self.attention_head_size = int(config.hidden_size / config.num_attention_heads) - self.all_head_size = self.num_attention_heads * self.attention_head_size - - self.query = nn.Linear(config.hidden_size, self.all_head_size) - if is_cross_attention: - self.key = nn.Linear(config.encoder_width, self.all_head_size) - self.value = nn.Linear(config.encoder_width, self.all_head_size) - else: - self.key = nn.Linear(config.hidden_size, self.all_head_size) - self.value = nn.Linear(config.hidden_size, self.all_head_size) - - self.dropout = nn.Dropout(config.attention_probs_dropout_prob) - self.position_embedding_type = getattr( - config, "position_embedding_type", "absolute" - ) - if ( - self.position_embedding_type == "relative_key" - or self.position_embedding_type == "relative_key_query" - ): - self.max_position_embeddings = config.max_position_embeddings - self.distance_embedding = nn.Embedding( - 2 * config.max_position_embeddings - 1, self.attention_head_size - ) - self.save_attention = False - - def save_attn_gradients(self, attn_gradients): - self.attn_gradients = attn_gradients - - def get_attn_gradients(self): - return self.attn_gradients - - def save_attention_map(self, attention_map): - self.attention_map = attention_map - - def get_attention_map(self): - return self.attention_map - - def transpose_for_scores(self, x): - new_x_shape = x.size()[:-1] + ( - self.num_attention_heads, - self.attention_head_size, - ) - x = x.view(*new_x_shape) - return x.permute(0, 2, 1, 3) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - ): - - # If this is instantiated as a cross-attention module, the keys - # and values come from an encoder; the attention mask needs to be - # such that the encoder's padding tokens are not attended to. - is_cross_attention = encoder_hidden_states is not None - - if is_cross_attention: - key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) - value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) - attention_mask = encoder_attention_mask - elif past_key_value is not None: - key_layer = self.transpose_for_scores(self.key(hidden_states)) - value_layer = self.transpose_for_scores(self.value(hidden_states)) - key_layer = torch.cat([past_key_value[0], key_layer], dim=2) - value_layer = torch.cat([past_key_value[1], value_layer], dim=2) - else: - key_layer = self.transpose_for_scores(self.key(hidden_states)) - value_layer = self.transpose_for_scores(self.value(hidden_states)) - - mixed_query_layer = self.query(hidden_states) - - query_layer = self.transpose_for_scores(mixed_query_layer) - - past_key_value = (key_layer, value_layer) - - # Take the dot product between "query" and "key" to get the raw attention scores. - attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) - - if ( - self.position_embedding_type == "relative_key" - or self.position_embedding_type == "relative_key_query" - ): - seq_length = hidden_states.size()[1] - position_ids_l = torch.arange( - seq_length, dtype=torch.long, device=hidden_states.device - ).view(-1, 1) - position_ids_r = torch.arange( - seq_length, dtype=torch.long, device=hidden_states.device - ).view(1, -1) - distance = position_ids_l - position_ids_r - positional_embedding = self.distance_embedding( - distance + self.max_position_embeddings - 1 - ) - positional_embedding = positional_embedding.to( - dtype=query_layer.dtype - ) # fp16 compatibility - - if self.position_embedding_type == "relative_key": - relative_position_scores = torch.einsum( - "bhld,lrd->bhlr", query_layer, positional_embedding - ) - attention_scores = attention_scores + relative_position_scores - elif self.position_embedding_type == "relative_key_query": - relative_position_scores_query = torch.einsum( - "bhld,lrd->bhlr", query_layer, positional_embedding - ) - relative_position_scores_key = torch.einsum( - "bhrd,lrd->bhlr", key_layer, positional_embedding - ) - attention_scores = ( - attention_scores - + relative_position_scores_query - + relative_position_scores_key - ) - - attention_scores = attention_scores / math.sqrt(self.attention_head_size) - if attention_mask is not None: - # Apply the attention mask is (precomputed for all layers in BertModel forward() function) - attention_scores = attention_scores + attention_mask - - # Normalize the attention scores to probabilities. - attention_probs = nn.Softmax(dim=-1)(attention_scores) - - if is_cross_attention and self.save_attention: - self.save_attention_map(attention_probs) - attention_probs.register_hook(self.save_attn_gradients) - - # This is actually dropping out entire tokens to attend to, which might - # seem a bit unusual, but is taken from the original Transformer paper. - attention_probs_dropped = self.dropout(attention_probs) - - # Mask heads if we want to - if head_mask is not None: - attention_probs_dropped = attention_probs_dropped * head_mask - - context_layer = torch.matmul(attention_probs_dropped, value_layer) - - context_layer = context_layer.permute(0, 2, 1, 3).contiguous() - new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) - context_layer = context_layer.view(*new_context_layer_shape) - - outputs = ( - (context_layer, attention_probs) if output_attentions else (context_layer,) - ) - - outputs = outputs + (past_key_value,) - return outputs - - -class BertSelfOutput(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.hidden_size) - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.hidden_dropout_prob) - - def forward(self, hidden_states, input_tensor): - hidden_states = self.dense(hidden_states) - hidden_states = self.dropout(hidden_states) - hidden_states = self.LayerNorm(hidden_states + input_tensor) - return hidden_states - - -class BertAttention(nn.Module): - def __init__(self, config, is_cross_attention=False): - super().__init__() - self.self = BertSelfAttention(config, is_cross_attention) - self.output = BertSelfOutput(config) - self.pruned_heads = set() - - def prune_heads(self, heads): - if len(heads) == 0: - return - heads, index = find_pruneable_heads_and_indices( - heads, - self.self.num_attention_heads, - self.self.attention_head_size, - self.pruned_heads, - ) - - # Prune linear layers - self.self.query = prune_linear_layer(self.self.query, index) - self.self.key = prune_linear_layer(self.self.key, index) - self.self.value = prune_linear_layer(self.self.value, index) - self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) - - # Update hyper params and store pruned heads - self.self.num_attention_heads = self.self.num_attention_heads - len(heads) - self.self.all_head_size = ( - self.self.attention_head_size * self.self.num_attention_heads - ) - self.pruned_heads = self.pruned_heads.union(heads) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - ): - self_outputs = self.self( - hidden_states, - attention_mask, - head_mask, - encoder_hidden_states, - encoder_attention_mask, - past_key_value, - output_attentions, - ) - attention_output = self.output(self_outputs[0], hidden_states) - - outputs = (attention_output,) + self_outputs[ - 1: - ] # add attentions if we output them - return outputs - - -class BertIntermediate(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.intermediate_size) - if isinstance(config.hidden_act, str): - self.intermediate_act_fn = ACT2FN[config.hidden_act] - else: - self.intermediate_act_fn = config.hidden_act - - def forward(self, hidden_states): - hidden_states = self.dense(hidden_states) - hidden_states = self.intermediate_act_fn(hidden_states) - return hidden_states - - -class BertOutput(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.intermediate_size, config.hidden_size) - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.hidden_dropout_prob) - - def forward(self, hidden_states, input_tensor): - hidden_states = self.dense(hidden_states) - hidden_states = self.dropout(hidden_states) - hidden_states = self.LayerNorm(hidden_states + input_tensor) - return hidden_states - - -class BertLayer(nn.Module): - def __init__(self, config, layer_num): - super().__init__() - self.config = config - self.chunk_size_feed_forward = config.chunk_size_feed_forward - self.seq_len_dim = 1 - self.attention = BertAttention(config) - self.layer_num = layer_num - if ( - self.config.add_cross_attention - and layer_num % self.config.cross_attention_freq == 0 - ): - self.crossattention = BertAttention( - config, is_cross_attention=self.config.add_cross_attention - ) - self.has_cross_attention = True - else: - self.has_cross_attention = False - self.intermediate = BertIntermediate(config) - self.output = BertOutput(config) - - self.intermediate_query = BertIntermediate(config) - self.output_query = BertOutput(config) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - query_length=0, - ): - # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 - self_attn_past_key_value = ( - past_key_value[:2] if past_key_value is not None else None - ) - self_attention_outputs = self.attention( - hidden_states, - attention_mask, - head_mask, - output_attentions=output_attentions, - past_key_value=self_attn_past_key_value, - ) - attention_output = self_attention_outputs[0] - outputs = self_attention_outputs[1:-1] - - present_key_value = self_attention_outputs[-1] - - if query_length > 0: - query_attention_output = attention_output[:, :query_length, :] - - if self.has_cross_attention: - assert ( - encoder_hidden_states is not None - ), "encoder_hidden_states must be given for cross-attention layers" - cross_attention_outputs = self.crossattention( - query_attention_output, - attention_mask, - head_mask, - encoder_hidden_states, - encoder_attention_mask, - output_attentions=output_attentions, - ) - query_attention_output = cross_attention_outputs[0] - outputs = ( - outputs + cross_attention_outputs[1:-1] - ) # add cross attentions if we output attention weights - - layer_output = apply_chunking_to_forward( - self.feed_forward_chunk_query, - self.chunk_size_feed_forward, - self.seq_len_dim, - query_attention_output, - ) - if attention_output.shape[1] > query_length: - layer_output_text = apply_chunking_to_forward( - self.feed_forward_chunk, - self.chunk_size_feed_forward, - self.seq_len_dim, - attention_output[:, query_length:, :], - ) - layer_output = torch.cat([layer_output, layer_output_text], dim=1) - else: - layer_output = apply_chunking_to_forward( - self.feed_forward_chunk, - self.chunk_size_feed_forward, - self.seq_len_dim, - attention_output, - ) - outputs = (layer_output,) + outputs - - outputs = outputs + (present_key_value,) - - return outputs - - def feed_forward_chunk(self, attention_output): - intermediate_output = self.intermediate(attention_output) - layer_output = self.output(intermediate_output, attention_output) - return layer_output - - def feed_forward_chunk_query(self, attention_output): - intermediate_output = self.intermediate_query(attention_output) - layer_output = self.output_query(intermediate_output, attention_output) - return layer_output - - -class BertEncoder(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - self.layer = nn.ModuleList( - [BertLayer(config, i) for i in range(config.num_hidden_layers)] - ) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_values=None, - use_cache=None, - output_attentions=False, - output_hidden_states=False, - return_dict=True, - query_length=0, - ): - all_hidden_states = () if output_hidden_states else None - all_self_attentions = () if output_attentions else None - all_cross_attentions = ( - () if output_attentions and self.config.add_cross_attention else None - ) - - next_decoder_cache = () if use_cache else None - - for i in range(self.config.num_hidden_layers): - layer_module = self.layer[i] - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - layer_head_mask = head_mask[i] if head_mask is not None else None - past_key_value = past_key_values[i] if past_key_values is not None else None - - if getattr(self.config, "gradient_checkpointing", False) and self.training: - - if use_cache: - logger.warn( - "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." - ) - use_cache = False - - def create_custom_forward(module): - def custom_forward(*inputs): - return module( - *inputs, past_key_value, output_attentions, query_length - ) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(layer_module), - hidden_states, - attention_mask, - layer_head_mask, - encoder_hidden_states, - encoder_attention_mask, - ) - else: - layer_outputs = layer_module( - hidden_states, - attention_mask, - layer_head_mask, - encoder_hidden_states, - encoder_attention_mask, - past_key_value, - output_attentions, - query_length, - ) - - hidden_states = layer_outputs[0] - if use_cache: - next_decoder_cache += (layer_outputs[-1],) - if output_attentions: - all_self_attentions = all_self_attentions + (layer_outputs[1],) - all_cross_attentions = all_cross_attentions + (layer_outputs[2],) - - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - if not return_dict: - return tuple( - v - for v in [ - hidden_states, - next_decoder_cache, - all_hidden_states, - all_self_attentions, - all_cross_attentions, - ] - if v is not None - ) - return BaseModelOutputWithPastAndCrossAttentions( - last_hidden_state=hidden_states, - past_key_values=next_decoder_cache, - hidden_states=all_hidden_states, - attentions=all_self_attentions, - cross_attentions=all_cross_attentions, - ) - - -class BertPooler(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.hidden_size) - self.activation = nn.Tanh() - - def forward(self, hidden_states): - # We "pool" the model by simply taking the hidden state corresponding - # to the first token. - first_token_tensor = hidden_states[:, 0] - pooled_output = self.dense(first_token_tensor) - pooled_output = self.activation(pooled_output) - return pooled_output - - -class BertPredictionHeadTransform(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.hidden_size) - if isinstance(config.hidden_act, str): - self.transform_act_fn = ACT2FN[config.hidden_act] - else: - self.transform_act_fn = config.hidden_act - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - - def forward(self, hidden_states): - hidden_states = self.dense(hidden_states) - hidden_states = self.transform_act_fn(hidden_states) - hidden_states = self.LayerNorm(hidden_states) - return hidden_states - - -class BertLMPredictionHead(nn.Module): - def __init__(self, config): - super().__init__() - self.transform = BertPredictionHeadTransform(config) - - # The output weights are the same as the input embeddings, but there is - # an output-only bias for each token. - self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) - - self.bias = nn.Parameter(torch.zeros(config.vocab_size)) - - # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` - self.decoder.bias = self.bias - - def forward(self, hidden_states): - hidden_states = self.transform(hidden_states) - hidden_states = self.decoder(hidden_states) - return hidden_states - - -class BertOnlyMLMHead(nn.Module): - def __init__(self, config): - super().__init__() - self.predictions = BertLMPredictionHead(config) - - def forward(self, sequence_output): - prediction_scores = self.predictions(sequence_output) - return prediction_scores - - -class BertPreTrainedModel(PreTrainedModel): - """ - An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained - models. - """ - - config_class = BertConfig - base_model_prefix = "bert" - _keys_to_ignore_on_load_missing = [r"position_ids"] - - def _init_weights(self, module): - """Initialize the weights""" - if isinstance(module, (nn.Linear, nn.Embedding)): - # Slightly different from the TF version which uses truncated_normal for initialization - # cf https://github.com/pytorch/pytorch/pull/5617 - module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) - elif isinstance(module, nn.LayerNorm): - module.bias.data.zero_() - module.weight.data.fill_(1.0) - if isinstance(module, nn.Linear) and module.bias is not None: - module.bias.data.zero_() - - -class BertModel(BertPreTrainedModel): - """ - The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of - cross-attention is added between the self-attention layers, following the architecture described in `Attention is - all you need `__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, - Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. - argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an - input to the forward pass. - """ - - def __init__(self, config, add_pooling_layer=False): - super().__init__(config) - self.config = config - - self.embeddings = BertEmbeddings(config) - - self.encoder = BertEncoder(config) - - self.pooler = BertPooler(config) if add_pooling_layer else None - - self.init_weights() - - def get_input_embeddings(self): - return self.embeddings.word_embeddings - - def set_input_embeddings(self, value): - self.embeddings.word_embeddings = value - - def _prune_heads(self, heads_to_prune): - """ - Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base - class PreTrainedModel - """ - for layer, heads in heads_to_prune.items(): - self.encoder.layer[layer].attention.prune_heads(heads) - - def get_extended_attention_mask( - self, - attention_mask: Tensor, - input_shape: Tuple[int], - device: device, - is_decoder: bool, - has_query: bool = False, - ) -> Tensor: - """ - Makes broadcastable attention and causal masks so that future and masked tokens are ignored. - - Arguments: - attention_mask (:obj:`torch.Tensor`): - Mask with ones indicating tokens to attend to, zeros for tokens to ignore. - input_shape (:obj:`Tuple[int]`): - The shape of the input to the model. - device: (:obj:`torch.device`): - The device of the input to the model. - - Returns: - :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. - """ - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if attention_mask.dim() == 3: - extended_attention_mask = attention_mask[:, None, :, :] - elif attention_mask.dim() == 2: - # Provided a padding mask of dimensions [batch_size, seq_length] - # - if the model is a decoder, apply a causal mask in addition to the padding mask - # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] - if is_decoder: - batch_size, seq_length = input_shape - - seq_ids = torch.arange(seq_length, device=device) - causal_mask = ( - seq_ids[None, None, :].repeat(batch_size, seq_length, 1) - <= seq_ids[None, :, None] - ) - - # add a prefix ones mask to the causal mask - # causal and attention masks must have same type with pytorch version < 1.3 - causal_mask = causal_mask.to(attention_mask.dtype) - - if causal_mask.shape[1] < attention_mask.shape[1]: - prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] - if has_query: # UniLM style attention mask - causal_mask = torch.cat( - [ - torch.zeros( - (batch_size, prefix_seq_len, seq_length), - device=device, - dtype=causal_mask.dtype, - ), - causal_mask, - ], - axis=1, - ) - causal_mask = torch.cat( - [ - torch.ones( - (batch_size, causal_mask.shape[1], prefix_seq_len), - device=device, - dtype=causal_mask.dtype, - ), - causal_mask, - ], - axis=-1, - ) - extended_attention_mask = ( - causal_mask[:, None, :, :] * attention_mask[:, None, None, :] - ) - else: - extended_attention_mask = attention_mask[:, None, None, :] - else: - raise ValueError( - "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( - input_shape, attention_mask.shape - ) - ) - - # 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. - extended_attention_mask = extended_attention_mask.to( - dtype=self.dtype - ) # fp16 compatibility - extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 - return extended_attention_mask - - def forward( - self, - input_ids=None, - attention_mask=None, - position_ids=None, - head_mask=None, - query_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_values=None, - use_cache=None, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - is_decoder=False, - ): - r""" - encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): - Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if - the model is configured as a decoder. - encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in - the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): - Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. - If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` - (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` - instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. - use_cache (:obj:`bool`, `optional`): - If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up - decoding (see :obj:`past_key_values`). - """ - 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 - ) - return_dict = ( - return_dict if return_dict is not None else self.config.use_return_dict - ) - - # use_cache = use_cache if use_cache is not None else self.config.use_cache - - if input_ids is None: - assert ( - query_embeds is not None - ), "You have to specify query_embeds when input_ids is None" - - # past_key_values_length - past_key_values_length = ( - past_key_values[0][0].shape[2] - self.config.query_length - if past_key_values is not None - else 0 - ) - - query_length = query_embeds.shape[1] if query_embeds is not None else 0 - - embedding_output = self.embeddings( - input_ids=input_ids, - position_ids=position_ids, - query_embeds=query_embeds, - past_key_values_length=past_key_values_length, - ) - - input_shape = embedding_output.size()[:-1] - batch_size, seq_length = input_shape - device = embedding_output.device - - if attention_mask is None: - attention_mask = torch.ones( - ((batch_size, seq_length + past_key_values_length)), device=device - ) - - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if is_decoder: - extended_attention_mask = self.get_extended_attention_mask( - attention_mask, - input_ids.shape, - device, - is_decoder, - has_query=(query_embeds is not None), - ) - else: - extended_attention_mask = self.get_extended_attention_mask( - attention_mask, input_shape, device, is_decoder - ) - - # 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 encoder_hidden_states is not None: - if type(encoder_hidden_states) == list: - encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[ - 0 - ].size() - else: - ( - encoder_batch_size, - encoder_sequence_length, - _, - ) = encoder_hidden_states.size() - encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) - - if type(encoder_attention_mask) == list: - encoder_extended_attention_mask = [ - self.invert_attention_mask(mask) for mask in encoder_attention_mask - ] - elif encoder_attention_mask is None: - encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) - encoder_extended_attention_mask = self.invert_attention_mask( - encoder_attention_mask - ) - else: - encoder_extended_attention_mask = self.invert_attention_mask( - encoder_attention_mask - ) - else: - encoder_extended_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 - # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] - # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] - head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) - - encoder_outputs = self.encoder( - embedding_output, - attention_mask=extended_attention_mask, - head_mask=head_mask, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_extended_attention_mask, - past_key_values=past_key_values, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - query_length=query_length, - ) - sequence_output = encoder_outputs[0] - pooled_output = ( - self.pooler(sequence_output) if self.pooler is not None else None - ) - - if not return_dict: - return (sequence_output, pooled_output) + encoder_outputs[1:] - - return BaseModelOutputWithPoolingAndCrossAttentions( - last_hidden_state=sequence_output, - pooler_output=pooled_output, - past_key_values=encoder_outputs.past_key_values, - hidden_states=encoder_outputs.hidden_states, - attentions=encoder_outputs.attentions, - cross_attentions=encoder_outputs.cross_attentions, - ) - - -class BertLMHeadModel(BertPreTrainedModel): - - _keys_to_ignore_on_load_unexpected = [r"pooler"] - _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] - - def __init__(self, config): - super().__init__(config) - - self.bert = BertModel(config, add_pooling_layer=False) - self.cls = BertOnlyMLMHead(config) - - self.init_weights() - - def get_output_embeddings(self): - return self.cls.predictions.decoder - - def set_output_embeddings(self, new_embeddings): - self.cls.predictions.decoder = new_embeddings - - def forward( - self, - input_ids=None, - attention_mask=None, - position_ids=None, - head_mask=None, - query_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - labels=None, - past_key_values=None, - use_cache=True, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - return_logits=False, - is_decoder=True, - reduction="mean", - ): - r""" - encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): - Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if - the model is configured as a decoder. - encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in - the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in - ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are - ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]`` - past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): - Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. - If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` - (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` - instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. - use_cache (:obj:`bool`, `optional`): - If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up - decoding (see :obj:`past_key_values`). - Returns: - Example:: - >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig - >>> import torch - >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased') - >>> config = BertConfig.from_pretrained("bert-base-cased") - >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config) - >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") - >>> outputs = model(**inputs) - >>> prediction_logits = outputs.logits - """ - return_dict = ( - return_dict if return_dict is not None else self.config.use_return_dict - ) - if labels is not None: - use_cache = False - if past_key_values is not None: - query_embeds = None - - outputs = self.bert( - input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - head_mask=head_mask, - query_embeds=query_embeds, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_attention_mask, - past_key_values=past_key_values, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - is_decoder=is_decoder, - ) - - sequence_output = outputs[0] - if query_embeds is not None: - sequence_output = outputs[0][:, query_embeds.shape[1] :, :] - - prediction_scores = self.cls(sequence_output) - - if return_logits: - return prediction_scores[:, :-1, :].contiguous() - - lm_loss = None - if labels is not None: - # we are doing next-token prediction; shift prediction scores and input ids by one - shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() - labels = labels[:, 1:].contiguous() - loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1) - lm_loss = loss_fct( - shifted_prediction_scores.view(-1, self.config.vocab_size), - labels.view(-1), - ) - if reduction == "none": - lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1) - - if not return_dict: - output = (prediction_scores,) + outputs[2:] - return ((lm_loss,) + output) if lm_loss is not None else output - - return CausalLMOutputWithCrossAttentions( - loss=lm_loss, - logits=prediction_scores, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - cross_attentions=outputs.cross_attentions, - ) - - def prepare_inputs_for_generation( - self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs - ): - # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly - if attention_mask is None: - attention_mask = input_ids.new_ones(input_ids.shape) - query_mask = input_ids.new_ones(query_embeds.shape[:-1]) - attention_mask = torch.cat([query_mask, attention_mask], dim=-1) - - # cut decoder_input_ids if past is used - if past is not None: - input_ids = input_ids[:, -1:] - - return { - "input_ids": input_ids, - "query_embeds": query_embeds, - "attention_mask": attention_mask, - "past_key_values": past, - "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None), - "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None), - "is_decoder": True, - } - - def _reorder_cache(self, past, beam_idx): - reordered_past = () - for layer_past in past: - reordered_past += ( - tuple( - past_state.index_select(0, beam_idx) for past_state in layer_past - ), - ) - return reordered_past - - -class BertForMaskedLM(BertPreTrainedModel): - - _keys_to_ignore_on_load_unexpected = [r"pooler"] - _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] - - def __init__(self, config): - super().__init__(config) - - self.bert = BertModel(config, add_pooling_layer=False) - self.cls = BertOnlyMLMHead(config) - - self.init_weights() - - def get_output_embeddings(self): - return self.cls.predictions.decoder - - def set_output_embeddings(self, new_embeddings): - self.cls.predictions.decoder = new_embeddings - - def forward( - self, - input_ids=None, - attention_mask=None, - position_ids=None, - head_mask=None, - query_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - labels=None, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - return_logits=False, - is_decoder=False, - ): - r""" - labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., - config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored - (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` - """ - - return_dict = ( - return_dict if return_dict is not None else self.config.use_return_dict - ) - - outputs = self.bert( - input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - head_mask=head_mask, - query_embeds=query_embeds, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_attention_mask, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - is_decoder=is_decoder, - ) - - if query_embeds is not None: - sequence_output = outputs[0][:, query_embeds.shape[1] :, :] - prediction_scores = self.cls(sequence_output) - - if return_logits: - return prediction_scores - - masked_lm_loss = None - if labels is not None: - loss_fct = CrossEntropyLoss() # -100 index = padding token - masked_lm_loss = loss_fct( - prediction_scores.view(-1, self.config.vocab_size), labels.view(-1) - ) - - if not return_dict: - output = (prediction_scores,) + outputs[2:] - return ( - ((masked_lm_loss,) + output) if masked_lm_loss is not None else output - ) - - return MaskedLMOutput( - loss=masked_lm_loss, - logits=prediction_scores, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) diff --git a/spaces/ShermanAI/ChatSherman/app.py b/spaces/ShermanAI/ChatSherman/app.py deleted file mode 100644 index a1a06eb45cbb7e7fce9a8f1304affa185711c9e2..0000000000000000000000000000000000000000 --- a/spaces/ShermanAI/ChatSherman/app.py +++ /dev/null @@ -1,42 +0,0 @@ -import subprocess -subprocess.check_call(["pip", "install", "--upgrade", "gradio"]) -subprocess.check_call(["pip", "install", "-q", "openai"]) -subprocess.check_call(["pip", "install", "-q", "gradio", "transformers", "python-dotenv"]) -import gradio as gr -from transformers import TFAutoModelForCausalLM, AutoTokenizer -import openai -from dotenv import load_dotenv -import os - -load_dotenv() # load environment variables from .env file -api_key = os.getenv("OPENAI_API_KEY") # access the value of the OPENAI_API_KEY environment variable - -def predict(message, history): - prompt = "I'm an AI chatbot named ChatSherman designed by a super-intelligent student named ShermanAI at the Department of Electronic and Information Engineering at The Hong Kong Polytechnic University to help you with your engineering questions. Also, I can assist with a wide range of topics and questions. I am now version 2.0, which is more powerful than version 1.0, able to do more complex tasks, and optimized for chat. " - history = [(prompt, '')] + history - history_openai_format = [] - for human, assistant in history: - history_openai_format.append({"role": "user", "content": human }) - history_openai_format.append({"role": "assistant", "content": assistant}) - history_openai_format.append({"role": "user", "content": message}) - response = openai.ChatCompletion.create( - model='gpt-3.5-turbo-16k-0613', #gpt-3.5-turbo-0301 faster - messages= history_openai_format, - temperature=0.5, - stream=True - ) - - partial_message = "" - for chunk in response: - if len(chunk['choices'][0]['delta']) != 0: - partial_message = partial_message + chunk['choices'][0]['delta']['content'] - yield partial_message - -title = "ChatSherman-2.0" -description = "This is an AI chatbot powered by ShermanAI. Enter your question below to get started." -examples = [ - ["What is ChatSherman, and how does it work?", []], - ["Is my personal information and data safe when I use the ChatSherman chatbot?", []], - ["What are some common applications of deep learning in engineering?", []] -] -gr.ChatInterface(predict, title=title, description=description, examples=examples).queue().launch(debug=True) \ No newline at end of file diff --git a/spaces/Shreyas3006/Text-Summarizer-sdp/utils.py b/spaces/Shreyas3006/Text-Summarizer-sdp/utils.py deleted file mode 100644 index f408c4782d1ad733bed152eff734474942b7a18e..0000000000000000000000000000000000000000 --- a/spaces/Shreyas3006/Text-Summarizer-sdp/utils.py +++ /dev/null @@ -1,133 +0,0 @@ -import re -import requests -import docx2txt -from io import StringIO -from PyPDF2 import PdfFileReader - -from bs4 import BeautifulSoup -from nltk.tokenize import sent_tokenize - -emoji_pattern = re.compile( - "[" - u"\U0001F600-\U0001F64F" # emoticons - u"\U0001F300-\U0001F5FF" # symbols & pictographs - u"\U0001F680-\U0001F6FF" # transport & map symbols - u"\U0001F1E0-\U0001F1FF" # flags (iOS) - u"\U00002702-\U000027B0" - u"\U000024C2-\U0001F251" - "]+", - flags=re.UNICODE, -) - - -def clean_text(x): - x = x.encode("ascii", "ignore").decode() # unicode - x = re.sub(r"https*\S+", " ", x) # url - x = re.sub(r"@\S+", " ", x) # mentions - x = re.sub(r"#\S+", " ", x) # hastags - x = re.sub(r"\s{2,}", " ", x) # over spaces - x = emoji_pattern.sub(r"", x) # emojis - x = re.sub("[^.,!?A-Za-z0-9]+", " ", x) # special charachters except .,!? - - return x - - -def fetch_article_text(url: str): - - r = requests.get(url) - soup = BeautifulSoup(r.text, "html.parser") - results = soup.find_all(["h1", "p"]) - text = [result.text for result in results] - ARTICLE = " ".join(text) - ARTICLE = ARTICLE.replace(".", ".") - ARTICLE = ARTICLE.replace("!", "!") - ARTICLE = ARTICLE.replace("?", "?") - sentences = ARTICLE.split("") - current_chunk = 0 - chunks = [] - for sentence in sentences: - if len(chunks) == current_chunk + 1: - if len(chunks[current_chunk]) + len(sentence.split(" ")) <= 500: - chunks[current_chunk].extend(sentence.split(" ")) - else: - current_chunk += 1 - chunks.append(sentence.split(" ")) - else: - print(current_chunk) - chunks.append(sentence.split(" ")) - - for chunk_id in range(len(chunks)): - chunks[chunk_id] = " ".join(chunks[chunk_id]) - - return ARTICLE, chunks - - -def preprocess_text_for_abstractive_summarization(tokenizer, text): - sentences = sent_tokenize(text) - - # initialize - length = 0 - chunk = "" - chunks = [] - count = -1 - for sentence in sentences: - count += 1 - combined_length = ( - len(tokenizer.tokenize(sentence)) + length - ) # add the no. of sentence tokens to the length counter - - if combined_length <= tokenizer.max_len_single_sentence: # if it doesn't exceed - chunk += sentence + " " # add the sentence to the chunk - length = combined_length # update the length counter - - # if it is the last sentence - if count == len(sentences) - 1: - chunks.append(chunk.strip()) # save the chunk - - else: - chunks.append(chunk.strip()) # save the chunk - - # reset - length = 0 - chunk = "" - - # take care of the overflow sentence - chunk += sentence + " " - length = len(tokenizer.tokenize(sentence)) - - return chunks - - -def read_pdf(file): - pdfReader = PdfFileReader(file) - count = pdfReader.numPages - all_page_text = "" - for i in range(count): - page = pdfReader.getPage(i) - all_page_text += page.extractText() - - return all_page_text - - -def read_text_from_file(file): - - # read text file - if file.type == "text/plain": - # To convert to a string based IO: - stringio = StringIO(file.getvalue().decode("utf-8")) - - # To read file as string: - file_content = stringio.read() - - # read pdf file - elif file.type == "application/pdf": - file_content = read_pdf(file) - - # read docx file - elif ( - file.type - == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" - ): - file_content = docx2txt.process(file) - - return file_content diff --git a/spaces/SmartPy/ScisummNet/README.md b/spaces/SmartPy/ScisummNet/README.md deleted file mode 100644 index c4f7df0e32653618701ce9dfd0d895df84d626e0..0000000000000000000000000000000000000000 --- a/spaces/SmartPy/ScisummNet/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: ScisummNet -emoji: 📈 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.15.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/Sourabh2/English2Manipuri/README.md b/spaces/Sourabh2/English2Manipuri/README.md deleted file mode 100644 index 2e4b6804ead293b5aca545a62acb282e60d0b82b..0000000000000000000000000000000000000000 --- a/spaces/Sourabh2/English2Manipuri/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: English2Manipuri -emoji: ⚡ -colorFrom: yellow -colorTo: purple -sdk: gradio -sdk_version: 3.40.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/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/nonascii.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/nonascii.py deleted file mode 100644 index 12738e3adc28b064c434a835a4df206ed88ae79f..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/nonascii.py +++ /dev/null @@ -1,4 +0,0 @@ -# coding: iso-8859-5 -# (Unlikely to be the default encoding for most testers.) -# <- Cyrillic characters -u = "" diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/ops/point_sample.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/ops/point_sample.py deleted file mode 100644 index 267f4b3c56630acd85f9bdc630b7be09abab0aba..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/ops/point_sample.py +++ /dev/null @@ -1,336 +0,0 @@ -# Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend # noqa - -from os import path as osp - -import torch -import torch.nn as nn -import torch.nn.functional as F -from torch.nn.modules.utils import _pair -from torch.onnx.operators import shape_as_tensor - - -def bilinear_grid_sample(im, grid, align_corners=False): - """Given an input and a flow-field grid, computes the output using input - values and pixel locations from grid. Supported only bilinear interpolation - method to sample the input pixels. - - Args: - im (torch.Tensor): Input feature map, shape (N, C, H, W) - grid (torch.Tensor): Point coordinates, shape (N, Hg, Wg, 2) - align_corners {bool}: If set to True, the extrema (-1 and 1) are - considered as referring to the center points of the input’s - corner pixels. If set to False, they are instead considered as - referring to the corner points of the input’s corner pixels, - making the sampling more resolution agnostic. - Returns: - torch.Tensor: A tensor with sampled points, shape (N, C, Hg, Wg) - """ - n, c, h, w = im.shape - gn, gh, gw, _ = grid.shape - assert n == gn - - x = grid[:, :, :, 0] - y = grid[:, :, :, 1] - - if align_corners: - x = ((x + 1) / 2) * (w - 1) - y = ((y + 1) / 2) * (h - 1) - else: - x = ((x + 1) * w - 1) / 2 - y = ((y + 1) * h - 1) / 2 - - x = x.view(n, -1) - y = y.view(n, -1) - - x0 = torch.floor(x).long() - y0 = torch.floor(y).long() - x1 = x0 + 1 - y1 = y0 + 1 - - wa = ((x1 - x) * (y1 - y)).unsqueeze(1) - wb = ((x1 - x) * (y - y0)).unsqueeze(1) - wc = ((x - x0) * (y1 - y)).unsqueeze(1) - wd = ((x - x0) * (y - y0)).unsqueeze(1) - - # Apply default for grid_sample function zero padding - im_padded = F.pad(im, pad=[1, 1, 1, 1], mode='constant', value=0) - padded_h = h + 2 - padded_w = w + 2 - # save points positions after padding - x0, x1, y0, y1 = x0 + 1, x1 + 1, y0 + 1, y1 + 1 - - # Clip coordinates to padded image size - x0 = torch.where(x0 < 0, torch.tensor(0), x0) - x0 = torch.where(x0 > padded_w - 1, torch.tensor(padded_w - 1), x0) - x1 = torch.where(x1 < 0, torch.tensor(0), x1) - x1 = torch.where(x1 > padded_w - 1, torch.tensor(padded_w - 1), x1) - y0 = torch.where(y0 < 0, torch.tensor(0), y0) - y0 = torch.where(y0 > padded_h - 1, torch.tensor(padded_h - 1), y0) - y1 = torch.where(y1 < 0, torch.tensor(0), y1) - y1 = torch.where(y1 > padded_h - 1, torch.tensor(padded_h - 1), y1) - - im_padded = im_padded.view(n, c, -1) - - x0_y0 = (x0 + y0 * padded_w).unsqueeze(1).expand(-1, c, -1) - x0_y1 = (x0 + y1 * padded_w).unsqueeze(1).expand(-1, c, -1) - x1_y0 = (x1 + y0 * padded_w).unsqueeze(1).expand(-1, c, -1) - x1_y1 = (x1 + y1 * padded_w).unsqueeze(1).expand(-1, c, -1) - - Ia = torch.gather(im_padded, 2, x0_y0) - Ib = torch.gather(im_padded, 2, x0_y1) - Ic = torch.gather(im_padded, 2, x1_y0) - Id = torch.gather(im_padded, 2, x1_y1) - - return (Ia * wa + Ib * wb + Ic * wc + Id * wd).reshape(n, c, gh, gw) - - -def is_in_onnx_export_without_custom_ops(): - from annotator.uniformer.mmcv.ops import get_onnxruntime_op_path - ort_custom_op_path = get_onnxruntime_op_path() - return torch.onnx.is_in_onnx_export( - ) and not osp.exists(ort_custom_op_path) - - -def normalize(grid): - """Normalize input grid from [-1, 1] to [0, 1] - Args: - grid (Tensor): The grid to be normalize, range [-1, 1]. - Returns: - Tensor: Normalized grid, range [0, 1]. - """ - - return (grid + 1.0) / 2.0 - - -def denormalize(grid): - """Denormalize input grid from range [0, 1] to [-1, 1] - Args: - grid (Tensor): The grid to be denormalize, range [0, 1]. - Returns: - Tensor: Denormalized grid, range [-1, 1]. - """ - - return grid * 2.0 - 1.0 - - -def generate_grid(num_grid, size, device): - """Generate regular square grid of points in [0, 1] x [0, 1] coordinate - space. - - Args: - num_grid (int): The number of grids to sample, one for each region. - size (tuple(int, int)): The side size of the regular grid. - device (torch.device): Desired device of returned tensor. - - Returns: - (torch.Tensor): A tensor of shape (num_grid, size[0]*size[1], 2) that - contains coordinates for the regular grids. - """ - - affine_trans = torch.tensor([[[1., 0., 0.], [0., 1., 0.]]], device=device) - grid = F.affine_grid( - affine_trans, torch.Size((1, 1, *size)), align_corners=False) - grid = normalize(grid) - return grid.view(1, -1, 2).expand(num_grid, -1, -1) - - -def rel_roi_point_to_abs_img_point(rois, rel_roi_points): - """Convert roi based relative point coordinates to image based absolute - point coordinates. - - Args: - rois (Tensor): RoIs or BBoxes, shape (N, 4) or (N, 5) - rel_roi_points (Tensor): Point coordinates inside RoI, relative to - RoI, location, range (0, 1), shape (N, P, 2) - Returns: - Tensor: Image based absolute point coordinates, shape (N, P, 2) - """ - - with torch.no_grad(): - assert rel_roi_points.size(0) == rois.size(0) - assert rois.dim() == 2 - assert rel_roi_points.dim() == 3 - assert rel_roi_points.size(2) == 2 - # remove batch idx - if rois.size(1) == 5: - rois = rois[:, 1:] - abs_img_points = rel_roi_points.clone() - # To avoid an error during exporting to onnx use independent - # variables instead inplace computation - xs = abs_img_points[:, :, 0] * (rois[:, None, 2] - rois[:, None, 0]) - ys = abs_img_points[:, :, 1] * (rois[:, None, 3] - rois[:, None, 1]) - xs += rois[:, None, 0] - ys += rois[:, None, 1] - abs_img_points = torch.stack([xs, ys], dim=2) - return abs_img_points - - -def get_shape_from_feature_map(x): - """Get spatial resolution of input feature map considering exporting to - onnx mode. - - Args: - x (torch.Tensor): Input tensor, shape (N, C, H, W) - Returns: - torch.Tensor: Spatial resolution (width, height), shape (1, 1, 2) - """ - if torch.onnx.is_in_onnx_export(): - img_shape = shape_as_tensor(x)[2:].flip(0).view(1, 1, 2).to( - x.device).float() - else: - img_shape = torch.tensor(x.shape[2:]).flip(0).view(1, 1, 2).to( - x.device).float() - return img_shape - - -def abs_img_point_to_rel_img_point(abs_img_points, img, spatial_scale=1.): - """Convert image based absolute point coordinates to image based relative - coordinates for sampling. - - Args: - abs_img_points (Tensor): Image based absolute point coordinates, - shape (N, P, 2) - img (tuple/Tensor): (height, width) of image or feature map. - spatial_scale (float): Scale points by this factor. Default: 1. - - Returns: - Tensor: Image based relative point coordinates for sampling, - shape (N, P, 2) - """ - - assert (isinstance(img, tuple) and len(img) == 2) or \ - (isinstance(img, torch.Tensor) and len(img.shape) == 4) - - if isinstance(img, tuple): - h, w = img - scale = torch.tensor([w, h], - dtype=torch.float, - device=abs_img_points.device) - scale = scale.view(1, 1, 2) - else: - scale = get_shape_from_feature_map(img) - - return abs_img_points / scale * spatial_scale - - -def rel_roi_point_to_rel_img_point(rois, - rel_roi_points, - img, - spatial_scale=1.): - """Convert roi based relative point coordinates to image based absolute - point coordinates. - - Args: - rois (Tensor): RoIs or BBoxes, shape (N, 4) or (N, 5) - rel_roi_points (Tensor): Point coordinates inside RoI, relative to - RoI, location, range (0, 1), shape (N, P, 2) - img (tuple/Tensor): (height, width) of image or feature map. - spatial_scale (float): Scale points by this factor. Default: 1. - - Returns: - Tensor: Image based relative point coordinates for sampling, - shape (N, P, 2) - """ - - abs_img_point = rel_roi_point_to_abs_img_point(rois, rel_roi_points) - rel_img_point = abs_img_point_to_rel_img_point(abs_img_point, img, - spatial_scale) - - return rel_img_point - - -def point_sample(input, points, align_corners=False, **kwargs): - """A wrapper around :func:`grid_sample` to support 3D point_coords tensors - Unlike :func:`torch.nn.functional.grid_sample` it assumes point_coords to - lie inside ``[0, 1] x [0, 1]`` square. - - Args: - input (Tensor): Feature map, shape (N, C, H, W). - points (Tensor): Image based absolute point coordinates (normalized), - range [0, 1] x [0, 1], shape (N, P, 2) or (N, Hgrid, Wgrid, 2). - align_corners (bool): Whether align_corners. Default: False - - Returns: - Tensor: Features of `point` on `input`, shape (N, C, P) or - (N, C, Hgrid, Wgrid). - """ - - add_dim = False - if points.dim() == 3: - add_dim = True - points = points.unsqueeze(2) - if is_in_onnx_export_without_custom_ops(): - # If custom ops for onnx runtime not compiled use python - # implementation of grid_sample function to make onnx graph - # with supported nodes - output = bilinear_grid_sample( - input, denormalize(points), align_corners=align_corners) - else: - output = F.grid_sample( - input, denormalize(points), align_corners=align_corners, **kwargs) - if add_dim: - output = output.squeeze(3) - return output - - -class SimpleRoIAlign(nn.Module): - - def __init__(self, output_size, spatial_scale, aligned=True): - """Simple RoI align in PointRend, faster than standard RoIAlign. - - Args: - output_size (tuple[int]): h, w - spatial_scale (float): scale the input boxes by this number - aligned (bool): if False, use the legacy implementation in - MMDetection, align_corners=True will be used in F.grid_sample. - If True, align the results more perfectly. - """ - - super(SimpleRoIAlign, self).__init__() - self.output_size = _pair(output_size) - self.spatial_scale = float(spatial_scale) - # to be consistent with other RoI ops - self.use_torchvision = False - self.aligned = aligned - - def forward(self, features, rois): - num_imgs = features.size(0) - num_rois = rois.size(0) - rel_roi_points = generate_grid( - num_rois, self.output_size, device=rois.device) - - if torch.onnx.is_in_onnx_export(): - rel_img_points = rel_roi_point_to_rel_img_point( - rois, rel_roi_points, features, self.spatial_scale) - rel_img_points = rel_img_points.reshape(num_imgs, -1, - *rel_img_points.shape[1:]) - point_feats = point_sample( - features, rel_img_points, align_corners=not self.aligned) - point_feats = point_feats.transpose(1, 2) - else: - point_feats = [] - for batch_ind in range(num_imgs): - # unravel batch dim - feat = features[batch_ind].unsqueeze(0) - inds = (rois[:, 0].long() == batch_ind) - if inds.any(): - rel_img_points = rel_roi_point_to_rel_img_point( - rois[inds], rel_roi_points[inds], feat, - self.spatial_scale).unsqueeze(0) - point_feat = point_sample( - feat, rel_img_points, align_corners=not self.aligned) - point_feat = point_feat.squeeze(0).transpose(0, 1) - point_feats.append(point_feat) - - point_feats = torch.cat(point_feats, dim=0) - - channels = features.size(1) - roi_feats = point_feats.reshape(num_rois, channels, *self.output_size) - - return roi_feats - - def __repr__(self): - format_str = self.__class__.__name__ - format_str += '(output_size={}, spatial_scale={}'.format( - self.output_size, self.spatial_scale) - return format_str diff --git a/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/runner/hooks/memory.py b/spaces/Superlang/ImageProcessor/annotator/uniformer/mmcv/runner/hooks/memory.py deleted file mode 100644 index 70cf9a838fb314e3bd3c07aadbc00921a81e83ed..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/uniformer/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/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_internal/utils/urls.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_internal/utils/urls.py deleted file mode 100644 index 6ba2e04f350792e2c0021cf7ba7f40b25dc6cd51..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_internal/utils/urls.py +++ /dev/null @@ -1,62 +0,0 @@ -import os -import string -import urllib.parse -import urllib.request -from typing import Optional - -from .compat import WINDOWS - - -def get_url_scheme(url: str) -> Optional[str]: - if ":" not in url: - return None - return url.split(":", 1)[0].lower() - - -def path_to_url(path: str) -> str: - """ - Convert a path to a file: URL. The path will be made absolute and have - quoted path parts. - """ - path = os.path.normpath(os.path.abspath(path)) - url = urllib.parse.urljoin("file:", urllib.request.pathname2url(path)) - return url - - -def url_to_path(url: str) -> str: - """ - Convert a file: URL to a path. - """ - assert url.startswith( - "file:" - ), f"You can only turn file: urls into filenames (not {url!r})" - - _, netloc, path, _, _ = urllib.parse.urlsplit(url) - - if not netloc or netloc == "localhost": - # According to RFC 8089, same as empty authority. - netloc = "" - elif WINDOWS: - # If we have a UNC path, prepend UNC share notation. - netloc = "\\\\" + netloc - else: - raise ValueError( - f"non-local file URIs are not supported on this platform: {url!r}" - ) - - path = urllib.request.url2pathname(netloc + path) - - # On Windows, urlsplit parses the path as something like "/C:/Users/foo". - # This creates issues for path-related functions like io.open(), so we try - # to detect and strip the leading slash. - if ( - WINDOWS - and not netloc # Not UNC. - and len(path) >= 3 - and path[0] == "/" # Leading slash to strip. - and path[1] in string.ascii_letters # Drive letter. - and path[2:4] in (":", ":/") # Colon + end of string, or colon + absolute path. - ): - path = path[1:] - - return path diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/rich/_export_format.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/rich/_export_format.py deleted file mode 100644 index 094d2dc226dde3122f09e4de5de0ef05599978bd..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/rich/_export_format.py +++ /dev/null @@ -1,76 +0,0 @@ -CONSOLE_HTML_FORMAT = """\ - - - - - - - -
{code}
- - -""" - -CONSOLE_SVG_FORMAT = """\ - - - - - - - - - {lines} - - - {chrome} - - {backgrounds} - - {matrix} - - - -""" - -_SVG_FONT_FAMILY = "Rich Fira Code" -_SVG_CLASSES_PREFIX = "rich-svg" diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/wheel/wheelfile.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/wheel/wheelfile.py deleted file mode 100644 index 465ba7bd35a698f681d57380d24d539072ec2edf..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/wheel/wheelfile.py +++ /dev/null @@ -1,197 +0,0 @@ -from __future__ import annotations - -import csv -import hashlib -import os.path -import re -import stat -import time -from collections import OrderedDict -from io import StringIO, TextIOWrapper -from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo - -from wheel.cli import WheelError -from wheel.util import log, urlsafe_b64decode, urlsafe_b64encode - -# Non-greedy matching of an optional build number may be too clever (more -# invalid wheel filenames will match). Separate regex for .dist-info? -WHEEL_INFO_RE = re.compile( - r"""^(?P(?P[^\s-]+?)-(?P[^\s-]+?))(-(?P\d[^\s-]*))? - -(?P[^\s-]+?)-(?P[^\s-]+?)-(?P\S+)\.whl$""", - re.VERBOSE, -) -MINIMUM_TIMESTAMP = 315532800 # 1980-01-01 00:00:00 UTC - - -def get_zipinfo_datetime(timestamp=None): - # Some applications need reproducible .whl files, but they can't do this without - # forcing the timestamp of the individual ZipInfo objects. See issue #143. - timestamp = int(os.environ.get("SOURCE_DATE_EPOCH", timestamp or time.time())) - timestamp = max(timestamp, MINIMUM_TIMESTAMP) - return time.gmtime(timestamp)[0:6] - - -class WheelFile(ZipFile): - """A ZipFile derivative class that also reads SHA-256 hashes from - .dist-info/RECORD and checks any read files against those. - """ - - _default_algorithm = hashlib.sha256 - - def __init__(self, file, mode="r", compression=ZIP_DEFLATED): - basename = os.path.basename(file) - self.parsed_filename = WHEEL_INFO_RE.match(basename) - if not basename.endswith(".whl") or self.parsed_filename is None: - raise WheelError(f"Bad wheel filename {basename!r}") - - ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True) - - self.dist_info_path = "{}.dist-info".format( - self.parsed_filename.group("namever") - ) - self.record_path = self.dist_info_path + "/RECORD" - self._file_hashes = OrderedDict() - self._file_sizes = {} - if mode == "r": - # Ignore RECORD and any embedded wheel signatures - self._file_hashes[self.record_path] = None, None - self._file_hashes[self.record_path + ".jws"] = None, None - self._file_hashes[self.record_path + ".p7s"] = None, None - - # Fill in the expected hashes by reading them from RECORD - try: - record = self.open(self.record_path) - except KeyError: - raise WheelError(f"Missing {self.record_path} file") from None - - with record: - for line in csv.reader( - TextIOWrapper(record, newline="", encoding="utf-8") - ): - path, hash_sum, size = line - if not hash_sum: - continue - - algorithm, hash_sum = hash_sum.split("=") - try: - hashlib.new(algorithm) - except ValueError: - raise WheelError( - f"Unsupported hash algorithm: {algorithm}" - ) from None - - if algorithm.lower() in {"md5", "sha1"}: - raise WheelError( - "Weak hash algorithm ({}) is not permitted by PEP " - "427".format(algorithm) - ) - - self._file_hashes[path] = ( - algorithm, - urlsafe_b64decode(hash_sum.encode("ascii")), - ) - - def open(self, name_or_info, mode="r", pwd=None): - def _update_crc(newdata): - eof = ef._eof - update_crc_orig(newdata) - running_hash.update(newdata) - if eof and running_hash.digest() != expected_hash: - raise WheelError(f"Hash mismatch for file '{ef_name}'") - - ef_name = ( - name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info - ) - if ( - mode == "r" - and not ef_name.endswith("/") - and ef_name not in self._file_hashes - ): - raise WheelError(f"No hash found for file '{ef_name}'") - - ef = ZipFile.open(self, name_or_info, mode, pwd) - if mode == "r" and not ef_name.endswith("/"): - algorithm, expected_hash = self._file_hashes[ef_name] - if expected_hash is not None: - # Monkey patch the _update_crc method to also check for the hash from - # RECORD - running_hash = hashlib.new(algorithm) - update_crc_orig, ef._update_crc = ef._update_crc, _update_crc - - return ef - - def write_files(self, base_dir): - log.info(f"creating '{self.filename}' and adding '{base_dir}' to it") - deferred = [] - for root, dirnames, filenames in os.walk(base_dir): - # Sort the directory names so that `os.walk` will walk them in a - # defined order on the next iteration. - dirnames.sort() - for name in sorted(filenames): - path = os.path.normpath(os.path.join(root, name)) - if os.path.isfile(path): - arcname = os.path.relpath(path, base_dir).replace(os.path.sep, "/") - if arcname == self.record_path: - pass - elif root.endswith(".dist-info"): - deferred.append((path, arcname)) - else: - self.write(path, arcname) - - deferred.sort() - for path, arcname in deferred: - self.write(path, arcname) - - def write(self, filename, arcname=None, compress_type=None): - with open(filename, "rb") as f: - st = os.fstat(f.fileno()) - data = f.read() - - zinfo = ZipInfo( - arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime) - ) - zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16 - zinfo.compress_type = compress_type or self.compression - self.writestr(zinfo, data, compress_type) - - def writestr(self, zinfo_or_arcname, data, compress_type=None): - if isinstance(zinfo_or_arcname, str): - zinfo_or_arcname = ZipInfo( - zinfo_or_arcname, date_time=get_zipinfo_datetime() - ) - zinfo_or_arcname.compress_type = self.compression - zinfo_or_arcname.external_attr = (0o664 | stat.S_IFREG) << 16 - - if isinstance(data, str): - data = data.encode("utf-8") - - ZipFile.writestr(self, zinfo_or_arcname, data, compress_type) - fname = ( - zinfo_or_arcname.filename - if isinstance(zinfo_or_arcname, ZipInfo) - else zinfo_or_arcname - ) - log.info(f"adding '{fname}'") - if fname != self.record_path: - hash_ = self._default_algorithm(data) - self._file_hashes[fname] = ( - hash_.name, - urlsafe_b64encode(hash_.digest()).decode("ascii"), - ) - self._file_sizes[fname] = len(data) - - def close(self): - # Write RECORD - if self.fp is not None and self.mode == "w" and self._file_hashes: - data = StringIO() - writer = csv.writer(data, delimiter=",", quotechar='"', lineterminator="\n") - writer.writerows( - ( - (fname, algorithm + "=" + hash_, self._file_sizes[fname]) - for fname, (algorithm, hash_) in self._file_hashes.items() - ) - ) - writer.writerow((format(self.record_path), "", "")) - self.writestr(self.record_path, data.getvalue()) - - ZipFile.close(self) diff --git a/spaces/Tetel/secondbing/SydneyGPT/conversation_style.py b/spaces/Tetel/secondbing/SydneyGPT/conversation_style.py deleted file mode 100644 index 94aa4c1bc77e57c86598df6438f29fb899c53694..0000000000000000000000000000000000000000 --- a/spaces/Tetel/secondbing/SydneyGPT/conversation_style.py +++ /dev/null @@ -1,68 +0,0 @@ -from enum import Enum - -try: - from typing import Literal, Union -except ImportError: - from typing_extensions import Literal -from typing import Optional - - -class ConversationStyle(Enum): - creative = [ - "nlu_direct_response_filter", - "deepleo", - "disable_emoji_spoken_text", - "responsible_ai_policy_235", - "enablemm", - "iycapbing", - "iyxapbing", - "uquopt", - "authsndfdbk", - "refpromptv1", - "enuaug", - "dagslnv1nr", - "dv3sugg", - "iyoloxap", - "iyoloneutral", - "h3imaginative", - "clgalileo", - "eredirecturl", - "gencontentv3", - "travelansgnd", - "nojbfedge", - ] - balanced = [ - "nlu_direct_response_filter", - "deepleo", - "disable_emoji_spoken_text", - "responsible_ai_policy_235", - "enablemm", - "galileo", - "dv3sugg", - "responseos", - "e2ecachewrite", - "cachewriteext", - "nodlcpcwrite", - "travelansgnd", - ] - precise = [ - "nlu_direct_response_filter", - "deepleo", - "disable_emoji_spoken_text", - "responsible_ai_policy_235", - "enablemm", - "galileo", - "dv3sugg", - "responseos", - "e2ecachewrite", - "cachewriteext", - "nodlcpcwrite", - "travelansgnd", - "h3precise", - "clgalileo", - ] - - -CONVERSATION_STYLE_TYPE = Optional[ - Union[ConversationStyle, Literal["creative", "balanced", "precise"]] -] diff --git a/spaces/Theivaprakasham/yolov6/yolov6/utils/figure_iou.py b/spaces/Theivaprakasham/yolov6/yolov6/utils/figure_iou.py deleted file mode 100644 index f3a0f3f7b7c477d38840ddbcddba1de405aaf164..0000000000000000000000000000000000000000 --- a/spaces/Theivaprakasham/yolov6/yolov6/utils/figure_iou.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -import math -import torch - - -class IOUloss: - """ Calculate IoU loss. - """ - def __init__(self, box_format='xywh', iou_type='ciou', reduction='none', eps=1e-7): - """ Setting of the class. - Args: - box_format: (string), must be one of 'xywh' or 'xyxy'. - iou_type: (string), can be one of 'ciou', 'diou', 'giou' or 'siou' - reduction: (string), specifies the reduction to apply to the output, must be one of 'none', 'mean','sum'. - eps: (float), a value to avoid devide by zero error. - """ - self.box_format = box_format - self.iou_type = iou_type.lower() - self.reduction = reduction - self.eps = eps - - def __call__(self, box1, box2): - """ calculate iou. box1 and box2 are torch tensor with shape [M, 4] and [Nm 4]. - """ - box2 = box2.T - if self.box_format == 'xyxy': - b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] - b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] - elif self.box_format == 'xywh': - b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 - b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 - b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 - b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 - - # Intersection area - inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ - (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) - - # Union Area - w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + self.eps - w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + self.eps - union = w1 * h1 + w2 * h2 - inter + self.eps - iou = inter / union - - cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex width - ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height - if self.iou_type == 'giou': - c_area = cw * ch + self.eps # convex area - iou = iou - (c_area - union) / c_area - elif self.iou_type in ['diou', 'ciou']: - c2 = cw ** 2 + ch ** 2 + self.eps # convex diagonal squared - rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + - (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared - if self.iou_type == 'diou': - iou = iou - rho2 / c2 - elif self.iou_type == 'ciou': - v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) - with torch.no_grad(): - alpha = v / (v - iou + (1 + self.eps)) - iou = iou - (rho2 / c2 + v * alpha) - elif self.iou_type == 'siou': - # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf - s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 - s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 - sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5) - sin_alpha_1 = torch.abs(s_cw) / sigma - sin_alpha_2 = torch.abs(s_ch) / sigma - threshold = pow(2, 0.5) / 2 - sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1) - angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2) - rho_x = (s_cw / cw) ** 2 - rho_y = (s_ch / ch) ** 2 - gamma = angle_cost - 2 - distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y) - omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2) - omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2) - shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4) - iou = iou - 0.5 * (distance_cost + shape_cost) - loss = 1.0 - iou - - if self.reduction == 'sum': - loss = loss.sum() - elif self.reduction == 'mean': - loss = loss.mean() - - return loss - - -def pairwise_bbox_iou(box1, box2, box_format='xywh'): - """Calculate iou. - This code is based on https://github.com/Megvii-BaseDetection/YOLOX/blob/main/yolox/utils/boxes.py - """ - if box_format == 'xyxy': - lt = torch.max(box1[:, None, :2], box2[:, :2]) - rb = torch.min(box1[:, None, 2:], box2[:, 2:]) - area_1 = torch.prod(box1[:, 2:] - box1[:, :2], 1) - area_2 = torch.prod(box2[:, 2:] - box2[:, :2], 1) - - elif box_format == 'xywh': - lt = torch.max( - (box1[:, None, :2] - box1[:, None, 2:] / 2), - (box2[:, :2] - box2[:, 2:] / 2), - ) - rb = torch.min( - (box1[:, None, :2] + box1[:, None, 2:] / 2), - (box2[:, :2] + box2[:, 2:] / 2), - ) - - area_1 = torch.prod(box1[:, 2:], 1) - area_2 = torch.prod(box2[:, 2:], 1) - valid = (lt < rb).type(lt.type()).prod(dim=2) - inter = torch.prod(rb - lt, 2) * valid - return inter / (area_1[:, None] + area_2 - inter) diff --git a/spaces/ToniDan/DanToniGPT2FormalInformal/README.md b/spaces/ToniDan/DanToniGPT2FormalInformal/README.md deleted file mode 100644 index 346a3a80a33fb53aea2330c0bb8ddaa39c6978af..0000000000000000000000000000000000000000 --- a/spaces/ToniDan/DanToniGPT2FormalInformal/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: DanToniGPT2FormalInformal -emoji: 💻 -colorFrom: indigo -colorTo: red -sdk: streamlit -sdk_version: 1.10.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/Torcat/torcat-test/scripts/segmentation_2_x_2.py b/spaces/Torcat/torcat-test/scripts/segmentation_2_x_2.py deleted file mode 100644 index 1d12fa798abdb9dc83a5cfea1ab6bbeed9c2e519..0000000000000000000000000000000000000000 --- a/spaces/Torcat/torcat-test/scripts/segmentation_2_x_2.py +++ /dev/null @@ -1,121 +0,0 @@ -import cv2 -import json -from segment_anything import SamAutomaticMaskGenerator, sam_model_registry -import supervision as sv -import torch -import uuid -import numpy as np -from pycocotools import mask as mask_util - -from config import ( - MODELS_FOLDER_PATH -) - -def segment_image_2_x_2(input_image): - # SAM Model - sam_checkpoint = f"{MODELS_FOLDER_PATH}/sam_vit_b_01ec64.pth" - model_type = "vit_b" - DEVICE = "cuda" if torch.cuda.is_available() else "cpu" - sam = sam_model_registry[model_type](checkpoint=sam_checkpoint).to(device=DEVICE) - mask_generator = SamAutomaticMaskGenerator(sam) - - # Load the image - buffer_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB) - - # Compute the half points - height, width = buffer_image.shape[:2] - center_height, center_width = height // 2, width // 2 - - # Calculate the width and height of a single quadrant - quadrant_width, quadrant_height = center_width, center_height - - # Split the image into four parts - quadrants = { - 'q1_q1': buffer_image[0:center_height, 0:center_width], - 'q1_q2': buffer_image[0:center_height, center_width:width], - 'q2_q1': buffer_image[center_height:height, 0:center_width], - 'q2_q2': buffer_image[center_height:height, center_width:width], - } - - images = {} - all_annotations = [] - - for quadrant_name, quadrant_image in quadrants.items(): - - # SAM - image_rgb = cv2.cvtColor(quadrant_image, cv2.COLOR_BGR2RGB) - masks = mask_generator.generate(image_rgb) - - mask_annotator = sv.MaskAnnotator() - detections = sv.Detections.from_sam(sam_result=masks) - new_image = mask_annotator.annotate(scene=image_rgb.copy(), detections=detections) - - # Generate annotations for each quadrant - annotations = [] - for i, mask_info in enumerate(masks): - # Extract the mask from the mask_info - mask = mask_info['segmentation'] - - # Convert the mask to a numpy array if it's not already one - if isinstance(mask, dict): - mask = mask_util.decode(mask) # decode the RLE - - # Convert the mask to a uint8 binary image - mask_uint8 = (mask * 255).astype(np.uint8) - _, binary_mask = cv2.threshold(mask_uint8, 1, 255, cv2.THRESH_BINARY) - - # Find the contours of the mask - contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) - points = [] - for contour in contours: - for point in contour: - # Get the original point coordinates - x, y = point[0].tolist() - - # Adjust the coordinates based on the quadrant - if quadrant_name in ['q1_q2', 'q2_q2']: - x += quadrant_width # Offset the x-coordinate - if quadrant_name in ['q2_q1', 'q2_q2']: - y += quadrant_height # Offset the y-coordinate - - # Add the adjusted point to the list - points.append([x, y]) - - # Create the SVG polygon string - svg_polygon = ' '.join([f'{x},{y}' for x, y in points]) - svg_string = f'' - - annotation = { - "@context": "http://www.w3.org/ns/anno.jsonld", - "id": "#" + str(uuid.uuid4()), - "type": "Annotation", - "body": [{ - "type": "TextualBody", - "value": f"A simple textual comment for region {i+1}.", - "purpose": "commenting" - }], - "target": { - "source": "your-source-here", # Replace - "selector": { - "type": "SvgSelector", - "value": svg_string - } - } - } - annotations.append(annotation) - - # Add the new image and its annotations to the dictionaries - images[quadrant_name] = new_image - all_annotations.extend(annotations) # Add annotations to the list of all annotations - - return images, all_annotations - -def merge_images_2_x_2(images): - # For each row, concatenate the images horizontally - top_row = cv2.hconcat([images['q1_q1'], images['q1_q2']]) - bottom_row = cv2.hconcat([images['q2_q1'], images['q2_q2']]) - - # Finally, concatenate the rows vertically to get the final image - final_image = cv2.vconcat([top_row, bottom_row]) - - return final_image \ No newline at end of file diff --git a/spaces/Ubai/Space/README.md b/spaces/Ubai/Space/README.md deleted file mode 100644 index df16735b67c3e4c2d28a759f548076cac8a96789..0000000000000000000000000000000000000000 --- a/spaces/Ubai/Space/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: PDF Assistance -colorFrom: purple -colorTo: red -sdk: docker -pinned: false -emoji: 👀 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/VishnuTransformer/TrOCR_Handwritten/README.md b/spaces/VishnuTransformer/TrOCR_Handwritten/README.md deleted file mode 100644 index 82b822c7d34f95a39d339f8e31987dfb41e6614c..0000000000000000000000000000000000000000 --- a/spaces/VishnuTransformer/TrOCR_Handwritten/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: TrOCR Handwritten -emoji: ⚡ -colorFrom: pink -colorTo: yellow -sdk: gradio -sdk_version: 3.1.7 -app_file: app.py -pinned: false -license: other ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Xenova/next-example-app/_next/static/chunks/framework-8883d1e9be70c3da.js b/spaces/Xenova/next-example-app/_next/static/chunks/framework-8883d1e9be70c3da.js deleted file mode 100644 index fafdd27ffff651d23c64770158aff84fa1d1e218..0000000000000000000000000000000000000000 --- a/spaces/Xenova/next-example-app/_next/static/chunks/framework-8883d1e9be70c3da.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[774],{4448:function(e,n,t){/** - * @license React - * react-dom.production.min.js - * - * 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. - */var r,l,a,u,o,i,s=t(7294),c=t(3840);function f(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t

CTRLsum: Towards Generic Controllable Text Summarization | Github Repo

" -examples = [ - ["""Paris, France's capital, is a major European city and a global center for art, fashion, gastronomy and culture. Its 19th-century cityscape is crisscrossed by wide boulevards and the River Seine. Beyond such landmarks as the Eiffel Tower and the 12th-century, Gothic Notre-Dame cathedral, the city is known for its cafe culture and designer boutiques along the Rue du Faubourg Saint-Honoré."""], - ["""London, the capital of England and the United Kingdom, is a 21st-century city with history stretching back to Roman times. At its centre stand the imposing Houses of Parliament, the iconic ‘Big Ben’ clock tower and Westminster Abbey, site of British monarch coronations. Across the Thames River, the London Eye observation wheel provides panoramic views of the South Bank cultural complex, and the entire city."""] -] -gr.Interface.load("huggingface/hyunwoongko/ctrlsum-cnndm", inputs=gr.inputs.Textbox(lines=10, label="Input Text"),title=title,description=description,article=article, examples=examples,enable_queue=True).launch() \ No newline at end of file diff --git a/spaces/akhaliq/deeplab2/model/loss/base_loss_test.py b/spaces/akhaliq/deeplab2/model/loss/base_loss_test.py deleted file mode 100644 index c6855eefa1a6d16a02e247e8bc3e9169b1ebdb17..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/deeplab2/model/loss/base_loss_test.py +++ /dev/null @@ -1,279 +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. - -"""Tests for base_loss.py.""" - -import numpy as np -import tensorflow as tf - -from deeplab2.model.loss import base_loss as loss - - -class BaseLossTest(tf.test.TestCase): - - def test_general_loss(self): - y_true = { - 'gt': tf.ones([2, 33, 33]) * 2, - 'weight': tf.ones([2, 33, 33]) - } - y_pred = {'pred': tf.zeros([2, 33, 33])} - - with self.subTest('L1'): - loss_layer = loss.TopKGeneralLoss( - loss.mean_absolute_error, - 'gt', - 'pred', - 'weight') - expected_loss = tf.ones([2]) * 2 - with self.subTest('MSE'): - loss_layer = loss.TopKGeneralLoss( - loss.mean_squared_error, - 'gt', - 'pred', - 'weight') - expected_loss = tf.ones([2]) * 4 - loss_result = loss_layer(y_true, y_pred) - np.testing.assert_almost_equal( - loss_result.numpy(), expected_loss.numpy(), decimal=5) - - def test_general_loss_weights(self): - weights = np.zeros((2, 33, 33)) - weights[:, 17:29, 15:23] = 1 - - gt = np.ones([2, 33, 33]) * 1.5 - gt[:, 17:29, 15:23] = 2 - - y_true = { - 'gt': tf.convert_to_tensor(gt, dtype=tf.float32), - 'weight': tf.convert_to_tensor(weights, dtype=tf.float32) - } - y_pred = {'pred': tf.zeros([2, 33, 33])} - loss_layer = loss.TopKGeneralLoss( - loss.mean_absolute_error, - 'gt', - 'pred', - 'weight') - - expected_loss = tf.ones([2]) * 2 - loss_result = loss_layer(y_true, y_pred) - - np.testing.assert_almost_equal( - loss_result.numpy(), expected_loss.numpy(), decimal=5) - - def test_topk_ce_loss_ignore(self): - num_classes = 19 - ignore_label = 255 - loss_layer = loss.TopKCrossEntropyLoss( - gt_key='gt', - pred_key='pred', - weight_key='weight', - num_classes=num_classes, - ignore_label=ignore_label) - - gt_tensor = np.ones(shape=[2, 33, 33], dtype=np.int32) * ignore_label - gt_tensor[:, 17:29, 15:23] = 1 - logits = tf.random.uniform(shape=[2, 33, 33, num_classes]) - - y_true = { - 'gt': tf.convert_to_tensor(gt_tensor), - 'weight': tf.ones([2, 33, 33]) - } - y_pred = {'pred': logits} - - expected_result = tf.nn.softmax_cross_entropy_with_logits( - tf.one_hot(np.squeeze(gt_tensor[:, 17:29, 15:23]), num_classes), - logits[:, 17:29, 15:23, :]) - expected_result = tf.reduce_mean(expected_result, axis=[1, 2]) - - per_sample_loss = loss_layer(y_true, y_pred) - - np.testing.assert_almost_equal( - per_sample_loss.numpy(), expected_result.numpy(), decimal=5) - - def test_topk_ce_loss_global_weight(self): - num_classes = 19 - weight = 3.145 - loss_layer = loss.TopKCrossEntropyLoss( - gt_key='gt', - pred_key='pred', - weight_key='weight', - num_classes=num_classes, - ignore_label=255) - logits = tf.random.uniform(shape=[2, 33, 33, num_classes]) - - y_true = { - 'gt': tf.ones([2, 33, 33], tf.int32), - 'weight': tf.ones([2, 33, 33]) - } - y_pred = {'pred': logits} - - expected_result = tf.nn.softmax_cross_entropy_with_logits( - tf.one_hot(y_true['gt'], num_classes), logits) - expected_result = tf.reduce_mean(expected_result, axis=[1, 2]) - expected_result *= weight - - per_sample_loss = loss_layer(y_true, y_pred, weight) - - np.testing.assert_almost_equal( - per_sample_loss.numpy(), expected_result.numpy(), decimal=5) - - def test_topk_ce_loss_topk(self): - num_classes = 19 - top_k = 0.5 - loss_layer = loss.TopKCrossEntropyLoss( - gt_key='gt', - pred_key='pred', - weight_key='weight', - num_classes=num_classes, - top_k_percent_pixels=top_k, - ignore_label=255) - - logits = tf.random.uniform(shape=[2, 33, 33, num_classes]) - y_true = { - 'gt': tf.ones([2, 33, 33], tf.int32), - 'weight': tf.ones([2, 33, 33]) - } - y_pred = {'pred': logits} - - expected_result = tf.nn.softmax_cross_entropy_with_logits( - tf.one_hot(y_true['gt'], num_classes), logits) - expected_result, _ = tf.math.top_k( - tf.reshape(expected_result, shape=[2, -1]), - tf.cast((top_k * tf.size(y_true['gt'], tf.float32) / 2), tf.int32)) - expected_result = tf.reduce_mean(expected_result, axis=[1]) - - per_sample_loss = loss_layer(y_true, y_pred) - - np.testing.assert_almost_equal( - per_sample_loss.numpy(), expected_result.numpy(), decimal=5) - - def test_is_one_hot(self): - num_classes = 19 - gt_list = [ - tf.ones([2, 33, 33], tf.int32), - tf.ones([2, 33], tf.int32), - tf.one_hot(tf.ones([2, 33, 33], tf.int32), num_classes), - tf.one_hot(tf.ones([2, 33], tf.int32), num_classes), - ] - pred_list = [ - tf.random.uniform(shape=[2, 33, 33, num_classes]), - tf.random.uniform(shape=[2, 33, num_classes]), - tf.random.uniform(shape=[2, 33, 33, num_classes]), - tf.random.uniform(shape=[2, 33, num_classes]), - ] - expected_result_list = [False, False, True, True] - output_list = [] - for gt, pred in zip(gt_list, pred_list): - output_list.append(loss.is_one_hot(gt, pred)) - np.testing.assert_equal(output_list, expected_result_list) - - def test_focal_ce_loss_integer_or_one_hot(self): - num_classes = 19 - gamma = 0.5 - alpha = 0.75 - loss_layer = loss.FocalCrossEntropyLoss( - gt_key='gt', - pred_key='pred', - weight_key='weight', - num_classes=num_classes, - focal_loss_alpha=alpha, - focal_loss_gamma=gamma, - ignore_label=255) - - logits = tf.random.uniform(shape=[2, 33 * 33, num_classes]) - gt = tf.ones([2, 33 * 33], tf.int32) - use_one_hot_encode_list = [False, True] - for use_one_hot_encode in use_one_hot_encode_list: - if use_one_hot_encode: - gt = tf.one_hot(gt, num_classes) - y_true = {'gt': gt} - y_pred = {'pred': logits, - 'weight': tf.ones([2, 33 * 33])} - predictions = tf.nn.softmax(logits, axis=-1) - if use_one_hot_encode: - pt = tf.reduce_sum(predictions * gt, axis=-1) - expected_result = tf.nn.softmax_cross_entropy_with_logits(gt, logits) - else: - pt = tf.reduce_sum(predictions * tf.one_hot(gt, num_classes), axis=-1) - expected_result = tf.nn.softmax_cross_entropy_with_logits( - tf.one_hot(gt, num_classes), logits) - expected_result = tf.multiply(tf.pow(1.0 - pt, gamma), expected_result) - expected_result = tf.reshape(expected_result, shape=[2, -1]) - # Since labels has no '19' (background) in this example, only alpha is - # multiplied. - expected_result = tf.reduce_mean(expected_result, axis=[1]) * alpha - per_sample_loss = loss_layer(y_true, y_pred) - - np.testing.assert_almost_equal( - per_sample_loss.numpy(), expected_result.numpy(), decimal=5) - - def test_mask_dice_loss(self): - gt = [ - [ - [1., 1., 1.], - [0., 0., 0.], - [0., 0., 0.], - ], - [ - [0., 0., 0.], - [1., 1., 1.], - [1., 1., 1.], - ], - ] - gt = tf.constant(gt, dtype=tf.float32) - gt = tf.expand_dims(gt, -1) - gt = tf.transpose(gt, perm=[3, 1, 2, 0]) - - y_true = {'gt': gt} - - pred = [ - [ - [1., 1., 0.], - [1., 1., 0.], - [1., 1., 0.], - ], - [ - [0., 0., 1.], - [0., 0., 1.], - [0., 0., 1.], - ], - ] - # Multiply 100 to make its Softmax output have 0 or 1 values. - pred = tf.constant(pred, dtype=tf.float32) * 100. - pred = tf.expand_dims(pred, -1) - pred = tf.transpose(pred, perm=[3, 1, 2, 0]) - y_pred = { - 'pred': pred, - 'weight': tf.ones([1]) * 0.5 - } - - loss_layer = loss.MaskDiceLoss( - gt_key='gt', - pred_key='pred', - weight_key='weight', - prediction_activation='softmax') - dice_loss = loss_layer(y_true, y_pred) - loss_result = dice_loss.numpy() - # For each channel, - # nominator = 2 * intersection(=2) + smooth(=1) = 5 - # denominator = 9 + smooth(=1) = 10 - # Channel-wise sum: [5/10, 5/10] -> [1.0] - # Weighted result: [1.0] * weight(=0.5) = 0.5 - expected_result = np.array([0.5]) - np.testing.assert_almost_equal(loss_result, expected_result) - - -if __name__ == '__main__': - tf.test.main() diff --git a/spaces/akhaliq/deeplab2/video/motion_deeplab.py b/spaces/akhaliq/deeplab2/video/motion_deeplab.py deleted file mode 100644 index ee35fb70b0650730d50ecd839b2a49915a753e2d..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/deeplab2/video/motion_deeplab.py +++ /dev/null @@ -1,212 +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 Motion-DeepLab architecture.""" - -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 motion_deeplab -from deeplab2.model.post_processor import post_processor_builder - - -class MotionDeepLab(tf.keras.Model): - """This class represents the Motion-DeepLab meta architecture. - - This class is the basis of the Motion-DeepLab architecture. This Model can be - used for Video Panoptic Segmentation or Segmenting and Tracking Every Pixel - (STEP). - """ - - def __init__(self, - config: config_pb2.ExperimentOptions, - dataset_descriptor: dataset.DatasetDescriptor): - """Initializes a Motion-DeepLab architecture. - - Args: - config: A config_pb2.ExperimentOptions configuration. - dataset_descriptor: A dataset.DatasetDescriptor. - """ - super(MotionDeepLab, self).__init__(name='MotionDeepLab') - - 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)) - - self._decoder = builder.create_decoder(config.model_options, bn_layer, - dataset_descriptor.ignore_label) - - self._prev_center_prediction = tf.Variable( - 0.0, - trainable=False, - validate_shape=False, - shape=tf.TensorShape(None), - dtype=tf.float32, - name='prev_prediction_buffer') - self._prev_center_list = tf.Variable( - tf.zeros((0, 5), dtype=tf.int32), - trainable=False, - validate_shape=False, - shape=tf.TensorShape(None), - name='prev_prediction_list') - self._next_tracking_id = tf.Variable( - 1, - trainable=False, - validate_shape=False, - dtype=tf.int32, - name='next+_tracking_id') - - self._post_processor = post_processor_builder.get_post_processor( - config, dataset_descriptor) - self._render_fn = functools.partial( - motion_deeplab.render_panoptic_map_as_heatmap, - sigma=8, - label_divisor=dataset_descriptor.panoptic_label_divisor, - void_label=dataset_descriptor.ignore_label) - self._track_fn = functools.partial( - motion_deeplab.assign_instances_to_previous_tracks, - label_divisor=dataset_descriptor.panoptic_label_divisor) - # The ASPP pooling size is always set to train crop size, which is found to - # be experimentally better. - 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) - - def call(self, input_tensor: tf.Tensor, training=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. - 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. - """ - if not training: - # During evaluation, we add the previous predicted heatmap as 7th input - # channel (cf. during training, we use groundtruth heatmap). - input_tensor = self._add_previous_heatmap_to_input(input_tensor) - # 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() - - pred = self._decoder( - self._encoder(input_tensor, training=training), training=training) - result_dict = dict() - for key, value in pred.items(): - if (key == common.PRED_OFFSET_MAP_KEY or - key == common.PRED_FRAME_OFFSET_MAP_KEY): - result_dict[key] = utils.resize_and_rescale_offsets( - value, [input_h, input_w]) - else: - result_dict[key] = utils.resize_bilinear( - value, [input_h, input_w]) - - # Change the semantic logits to probabilities with softmax. - result_dict[common.PRED_SEMANTIC_PROBS_KEY] = tf.nn.softmax( - result_dict[common.PRED_SEMANTIC_LOGITS_KEY]) - if not training: - result_dict.update(self._post_processor(result_dict)) - - next_heatmap, next_centers = self._render_fn( - result_dict[common.PRED_PANOPTIC_KEY]) - panoptic_map, next_centers, next_id = self._track_fn( - self._prev_center_list.value(), - next_centers, - next_heatmap, - result_dict[common.PRED_FRAME_OFFSET_MAP_KEY], - result_dict[common.PRED_PANOPTIC_KEY], - self._next_tracking_id.value() - ) - - result_dict[common.PRED_PANOPTIC_KEY] = panoptic_map - self._next_tracking_id.assign(next_id) - self._prev_center_prediction.assign( - tf.expand_dims(next_heatmap, axis=3, name='expand_prev_centermap')) - self._prev_center_list.assign(next_centers) - - 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 _add_previous_heatmap_to_input(self, input_tensor: tf.Tensor - ) -> tf.Tensor: - frame1, frame2 = tf.split(input_tensor, [3, 3], axis=3) - # We use a simple way to detect if the first frame of a sequence is being - # processed. For the first frame, frame1 and frame2 are identical. - if tf.reduce_all(tf.equal(frame1, frame2)): - h = tf.shape(input_tensor)[1] - w = tf.shape(input_tensor)[2] - prev_center = tf.zeros((1, h, w, 1), dtype=tf.float32) - self._prev_center_list.assign(tf.zeros((0, 5), dtype=tf.int32)) - self._next_tracking_id.assign(1) - else: - prev_center = self._prev_center_prediction - output_tensor = tf.concat([frame1, frame2, prev_center], axis=3) - output_tensor.set_shape([None, None, None, 7]) - return output_tensor - - 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) - - @property - def checkpoint_items(self) -> Dict[Text, Any]: - items = dict(encoder=self._encoder) - items.update(self._decoder.checkpoint_items) - return items diff --git a/spaces/akhaliq/test-chatgpt/README.md b/spaces/akhaliq/test-chatgpt/README.md deleted file mode 100644 index 5a7e2f964bfd2b35fec88afb6630553547aeeab3..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/test-chatgpt/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Test Chatgpt -emoji: 👁 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.12.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/alex-mindspace/gpt-agents/swarmai/agents/__init__.py b/spaces/alex-mindspace/gpt-agents/swarmai/agents/__init__.py deleted file mode 100644 index 782d7e84e2c39e4168a0382b04b58a1a56c37485..0000000000000000000000000000000000000000 --- a/spaces/alex-mindspace/gpt-agents/swarmai/agents/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .ManagerAgent import ManagerAgent -from .GeneralPurposeAgent import GeneralPurposeAgent -from .GooglerAgent import GooglerAgent -from .CrunchbaseSearcher import CrunchbaseSearcher \ No newline at end of file diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/utils/models.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/utils/models.py deleted file mode 100644 index b6bb21a8b26680b38c3af8278ed139b6628356c5..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_internal/utils/models.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Utilities for defining models -""" - -import operator -from typing import Any, Callable, Type - - -class KeyBasedCompareMixin: - """Provides comparison capabilities that is based on a key""" - - __slots__ = ["_compare_key", "_defining_class"] - - def __init__(self, key: Any, defining_class: Type["KeyBasedCompareMixin"]) -> None: - self._compare_key = key - self._defining_class = defining_class - - def __hash__(self) -> int: - return hash(self._compare_key) - - def __lt__(self, other: Any) -> bool: - return self._compare(other, operator.__lt__) - - def __le__(self, other: Any) -> bool: - return self._compare(other, operator.__le__) - - def __gt__(self, other: Any) -> bool: - return self._compare(other, operator.__gt__) - - def __ge__(self, other: Any) -> bool: - return self._compare(other, operator.__ge__) - - def __eq__(self, other: Any) -> bool: - return self._compare(other, operator.__eq__) - - def _compare(self, other: Any, method: Callable[[Any, Any], bool]) -> bool: - if not isinstance(other, self._defining_class): - return NotImplemented - - return method(self._compare_key, other._compare_key) diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__init__.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__init__.py deleted file mode 100644 index 6981b8d1187b8110fcd33d19430a190053ab048d..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__init__.py +++ /dev/null @@ -1,341 +0,0 @@ -""" - pygments.lexers - ~~~~~~~~~~~~~~~ - - Pygments lexers. - - :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -import sys -import types -import fnmatch -from os.path import basename - -from pip._vendor.pygments.lexers._mapping import LEXERS -from pip._vendor.pygments.modeline import get_filetype_from_buffer -from pip._vendor.pygments.plugin import find_plugin_lexers -from pip._vendor.pygments.util import ClassNotFound, guess_decode - -COMPAT = { - 'Python3Lexer': 'PythonLexer', - 'Python3TracebackLexer': 'PythonTracebackLexer', -} - -__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class', - 'guess_lexer', 'load_lexer_from_file'] + list(LEXERS) + list(COMPAT) - -_lexer_cache = {} -_pattern_cache = {} - - -def _fn_matches(fn, glob): - """Return whether the supplied file name fn matches pattern filename.""" - if glob not in _pattern_cache: - pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob)) - return pattern.match(fn) - return _pattern_cache[glob].match(fn) - - -def _load_lexers(module_name): - """Load a lexer (and all others in the module too).""" - mod = __import__(module_name, None, None, ['__all__']) - for lexer_name in mod.__all__: - cls = getattr(mod, lexer_name) - _lexer_cache[cls.name] = cls - - -def get_all_lexers(): - """Return a generator of tuples in the form ``(name, aliases, - filenames, mimetypes)`` of all know lexers. - """ - for item in LEXERS.values(): - yield item[1:] - for lexer in find_plugin_lexers(): - yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes - - -def find_lexer_class(name): - """Lookup a lexer class by name. - - Return None if not found. - """ - if name in _lexer_cache: - return _lexer_cache[name] - # lookup builtin lexers - for module_name, lname, aliases, _, _ in LEXERS.values(): - if name == lname: - _load_lexers(module_name) - return _lexer_cache[name] - # continue with lexers from setuptools entrypoints - for cls in find_plugin_lexers(): - if cls.name == name: - return cls - - -def find_lexer_class_by_name(_alias): - """Lookup a lexer class by alias. - - Like `get_lexer_by_name`, but does not instantiate the class. - - .. versionadded:: 2.2 - """ - if not _alias: - raise ClassNotFound('no lexer for alias %r found' % _alias) - # lookup builtin lexers - for module_name, name, aliases, _, _ in LEXERS.values(): - if _alias.lower() in aliases: - if name not in _lexer_cache: - _load_lexers(module_name) - return _lexer_cache[name] - # continue with lexers from setuptools entrypoints - for cls in find_plugin_lexers(): - if _alias.lower() in cls.aliases: - return cls - raise ClassNotFound('no lexer for alias %r found' % _alias) - - -def get_lexer_by_name(_alias, **options): - """Get a lexer by an alias. - - Raises ClassNotFound if not found. - """ - if not _alias: - raise ClassNotFound('no lexer for alias %r found' % _alias) - - # lookup builtin lexers - for module_name, name, aliases, _, _ in LEXERS.values(): - if _alias.lower() in aliases: - if name not in _lexer_cache: - _load_lexers(module_name) - return _lexer_cache[name](**options) - # continue with lexers from setuptools entrypoints - for cls in find_plugin_lexers(): - if _alias.lower() in cls.aliases: - return cls(**options) - raise ClassNotFound('no lexer for alias %r found' % _alias) - - -def load_lexer_from_file(filename, lexername="CustomLexer", **options): - """Load a lexer from a file. - - This method expects a file located relative to the current working - directory, which contains a Lexer class. By default, it expects the - Lexer to be name CustomLexer; you can specify your own class name - as the second argument to this function. - - Users should be very careful with the input, because this method - is equivalent to running eval on the input file. - - Raises ClassNotFound if there are any problems importing the Lexer. - - .. versionadded:: 2.2 - """ - try: - # This empty dict will contain the namespace for the exec'd file - custom_namespace = {} - with open(filename, 'rb') as f: - exec(f.read(), custom_namespace) - # Retrieve the class `lexername` from that namespace - if lexername not in custom_namespace: - raise ClassNotFound('no valid %s class found in %s' % - (lexername, filename)) - lexer_class = custom_namespace[lexername] - # And finally instantiate it with the options - return lexer_class(**options) - except OSError as err: - raise ClassNotFound('cannot read %s: %s' % (filename, err)) - except ClassNotFound: - raise - except Exception as err: - raise ClassNotFound('error when loading custom lexer: %s' % err) - - -def find_lexer_class_for_filename(_fn, code=None): - """Get a lexer for a filename. - - If multiple lexers match the filename pattern, use ``analyse_text()`` to - figure out which one is more appropriate. - - Returns None if not found. - """ - matches = [] - fn = basename(_fn) - for modname, name, _, filenames, _ in LEXERS.values(): - for filename in filenames: - if _fn_matches(fn, filename): - if name not in _lexer_cache: - _load_lexers(modname) - matches.append((_lexer_cache[name], filename)) - for cls in find_plugin_lexers(): - for filename in cls.filenames: - if _fn_matches(fn, filename): - matches.append((cls, filename)) - - if isinstance(code, bytes): - # decode it, since all analyse_text functions expect unicode - code = guess_decode(code) - - def get_rating(info): - cls, filename = info - # explicit patterns get a bonus - bonus = '*' not in filename and 0.5 or 0 - # The class _always_ defines analyse_text because it's included in - # the Lexer class. The default implementation returns None which - # gets turned into 0.0. Run scripts/detect_missing_analyse_text.py - # to find lexers which need it overridden. - if code: - return cls.analyse_text(code) + bonus, cls.__name__ - return cls.priority + bonus, cls.__name__ - - if matches: - matches.sort(key=get_rating) - # print "Possible lexers, after sort:", matches - return matches[-1][0] - - -def get_lexer_for_filename(_fn, code=None, **options): - """Get a lexer for a filename. - - If multiple lexers match the filename pattern, use ``analyse_text()`` to - figure out which one is more appropriate. - - Raises ClassNotFound if not found. - """ - res = find_lexer_class_for_filename(_fn, code) - if not res: - raise ClassNotFound('no lexer for filename %r found' % _fn) - return res(**options) - - -def get_lexer_for_mimetype(_mime, **options): - """Get a lexer for a mimetype. - - Raises ClassNotFound if not found. - """ - for modname, name, _, _, mimetypes in LEXERS.values(): - if _mime in mimetypes: - if name not in _lexer_cache: - _load_lexers(modname) - return _lexer_cache[name](**options) - for cls in find_plugin_lexers(): - if _mime in cls.mimetypes: - return cls(**options) - raise ClassNotFound('no lexer for mimetype %r found' % _mime) - - -def _iter_lexerclasses(plugins=True): - """Return an iterator over all lexer classes.""" - for key in sorted(LEXERS): - module_name, name = LEXERS[key][:2] - if name not in _lexer_cache: - _load_lexers(module_name) - yield _lexer_cache[name] - if plugins: - yield from find_plugin_lexers() - - -def guess_lexer_for_filename(_fn, _text, **options): - """ - Lookup all lexers that handle those filenames primary (``filenames``) - or secondary (``alias_filenames``). Then run a text analysis for those - lexers and choose the best result. - - usage:: - - >>> from pygments.lexers import guess_lexer_for_filename - >>> guess_lexer_for_filename('hello.html', '<%= @foo %>') - - >>> guess_lexer_for_filename('hello.html', '

{{ title|e }}

') - - >>> guess_lexer_for_filename('style.css', 'a { color: }') - - """ - fn = basename(_fn) - primary = {} - matching_lexers = set() - for lexer in _iter_lexerclasses(): - for filename in lexer.filenames: - if _fn_matches(fn, filename): - matching_lexers.add(lexer) - primary[lexer] = True - for filename in lexer.alias_filenames: - if _fn_matches(fn, filename): - matching_lexers.add(lexer) - primary[lexer] = False - if not matching_lexers: - raise ClassNotFound('no lexer for filename %r found' % fn) - if len(matching_lexers) == 1: - return matching_lexers.pop()(**options) - result = [] - for lexer in matching_lexers: - rv = lexer.analyse_text(_text) - if rv == 1.0: - return lexer(**options) - result.append((rv, lexer)) - - def type_sort(t): - # sort by: - # - analyse score - # - is primary filename pattern? - # - priority - # - last resort: class name - return (t[0], primary[t[1]], t[1].priority, t[1].__name__) - result.sort(key=type_sort) - - return result[-1][1](**options) - - -def guess_lexer(_text, **options): - """Guess a lexer by strong distinctions in the text (eg, shebang).""" - - if not isinstance(_text, str): - inencoding = options.get('inencoding', options.get('encoding')) - if inencoding: - _text = _text.decode(inencoding or 'utf8') - else: - _text, _ = guess_decode(_text) - - # try to get a vim modeline first - ft = get_filetype_from_buffer(_text) - - if ft is not None: - try: - return get_lexer_by_name(ft, **options) - except ClassNotFound: - pass - - best_lexer = [0.0, None] - for lexer in _iter_lexerclasses(): - rv = lexer.analyse_text(_text) - if rv == 1.0: - return lexer(**options) - if rv > best_lexer[0]: - best_lexer[:] = (rv, lexer) - if not best_lexer[0] or best_lexer[1] is None: - raise ClassNotFound('no lexer matching the text found') - return best_lexer[1](**options) - - -class _automodule(types.ModuleType): - """Automatically import lexers.""" - - def __getattr__(self, name): - info = LEXERS.get(name) - if info: - _load_lexers(info[0]) - cls = _lexer_cache[info[1]] - setattr(self, name, cls) - return cls - if name in COMPAT: - return getattr(self, COMPAT[name]) - raise AttributeError(name) - - -oldmod = sys.modules[__name__] -newmod = _automodule(__name__) -newmod.__dict__.update(oldmod.__dict__) -sys.modules[__name__] = newmod -del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/requests/structures.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/requests/structures.py deleted file mode 100644 index 8ee0ba7a082a04bfb91a6e1c7d80c5d51c0a2573..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/requests/structures.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -requests.structures -~~~~~~~~~~~~~~~~~~~ - -Data structures that power Requests. -""" - -from collections import OrderedDict - -from .compat import Mapping, MutableMapping - - -class CaseInsensitiveDict(MutableMapping): - """A case-insensitive ``dict``-like object. - - Implements all methods and operations of - ``MutableMapping`` as well as dict's ``copy``. Also - provides ``lower_items``. - - All keys are expected to be strings. The structure remembers the - case of the last key to be set, and ``iter(instance)``, - ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` - will contain case-sensitive keys. However, querying and contains - testing is case insensitive:: - - cid = CaseInsensitiveDict() - cid['Accept'] = 'application/json' - cid['aCCEPT'] == 'application/json' # True - list(cid) == ['Accept'] # True - - For example, ``headers['content-encoding']`` will return the - value of a ``'Content-Encoding'`` response header, regardless - of how the header name was originally stored. - - If the constructor, ``.update``, or equality comparison - operations are given keys that have equal ``.lower()``s, the - behavior is undefined. - """ - - def __init__(self, data=None, **kwargs): - self._store = OrderedDict() - if data is None: - data = {} - self.update(data, **kwargs) - - def __setitem__(self, key, value): - # Use the lowercased key for lookups, but store the actual - # key alongside the value. - self._store[key.lower()] = (key, value) - - def __getitem__(self, key): - return self._store[key.lower()][1] - - def __delitem__(self, key): - del self._store[key.lower()] - - def __iter__(self): - return (casedkey for casedkey, mappedvalue in self._store.values()) - - def __len__(self): - return len(self._store) - - def lower_items(self): - """Like iteritems(), but with all lowercase keys.""" - return ( - (lowerkey, keyval[1]) - for (lowerkey, keyval) - in self._store.items() - ) - - def __eq__(self, other): - if isinstance(other, Mapping): - other = CaseInsensitiveDict(other) - else: - return NotImplemented - # Compare insensitively - return dict(self.lower_items()) == dict(other.lower_items()) - - # Copy is required - def copy(self): - return CaseInsensitiveDict(self._store.values()) - - def __repr__(self): - return str(dict(self.items())) - - -class LookupDict(dict): - """Dictionary lookup object.""" - - def __init__(self, name=None): - self.name = name - super(LookupDict, self).__init__() - - def __repr__(self): - return '' % (self.name) - - def __getitem__(self, key): - # We allow fall-through here, so values default to None - - return self.__dict__.get(key, None) - - def get(self, key, default=None): - return self.__dict__.get(key, default) diff --git a/spaces/alihalabyah/falcon-180b-demo/app.py b/spaces/alihalabyah/falcon-180b-demo/app.py deleted file mode 100644 index 57379e917c123810ccbb6ad20cdaa580825fe366..0000000000000000000000000000000000000000 --- a/spaces/alihalabyah/falcon-180b-demo/app.py +++ /dev/null @@ -1,145 +0,0 @@ -import json -import os -import shutil -import requests - -import gradio as gr -from huggingface_hub import Repository, InferenceClient - -HF_TOKEN = os.environ.get("HF_TOKEN", None) -API_URL = "https://api-inference.huggingface.co/models/tiiuae/falcon-180B-chat" -BOT_NAME = "Falcon" - -STOP_SEQUENCES = ["\nUser:", "<|endoftext|>", " User:", "###"] - -EXAMPLES = [ - ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"], - ["What's the Everett interpretation of quantum mechanics?"], - ["Give me a list of the top 10 dive sites you would recommend around the world."], - ["Can you tell me more about deep-water soloing?"], - ["Can you write a short tweet about the release of our latest AI model, Falcon LLM?"] - ] - -client = InferenceClient( - API_URL, - headers={"Authorization": f"Bearer {HF_TOKEN}"}, -) - -def format_prompt(message, history, system_prompt): - prompt = "" - if system_prompt: - prompt += f"System: {system_prompt}\n" - for user_prompt, bot_response in history: - prompt += f"User: {user_prompt}\n" - prompt += f"Falcon: {bot_response}\n" # Response already contains "Falcon: " - prompt += f"""User: {message} -Falcon:""" - return prompt - -seed = 42 - -def generate( - prompt, history, system_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0, -): - temperature = float(temperature) - if temperature < 1e-2: - temperature = 1e-2 - top_p = float(top_p) - global seed - generate_kwargs = dict( - temperature=temperature, - max_new_tokens=max_new_tokens, - top_p=top_p, - repetition_penalty=repetition_penalty, - stop_sequences=STOP_SEQUENCES, - do_sample=True, - seed=seed, - ) - seed = seed + 1 - formatted_prompt = format_prompt(prompt, history, system_prompt) - - stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False) - output = "" - - for response in stream: - output += response.token.text - - for stop_str in STOP_SEQUENCES: - if output.endswith(stop_str): - output = output[:-len(stop_str)] - output = output.rstrip() - yield output - yield output - return output - - -additional_inputs=[ - gr.Textbox("", label="Optional system prompt"), - gr.Slider( - label="Temperature", - value=0.9, - minimum=0.0, - maximum=1.0, - step=0.05, - interactive=True, - info="Higher values produce more diverse outputs", - ), - gr.Slider( - label="Max new tokens", - value=256, - minimum=0, - maximum=8192, - step=64, - interactive=True, - info="The maximum numbers of new tokens", - ), - gr.Slider( - label="Top-p (nucleus sampling)", - value=0.90, - minimum=0.0, - maximum=1, - step=0.05, - interactive=True, - info="Higher values sample more low-probability tokens", - ), - gr.Slider( - label="Repetition penalty", - value=1.2, - minimum=1.0, - maximum=2.0, - step=0.05, - interactive=True, - info="Penalize repeated tokens", - ) -] - - -with gr.Blocks() as demo: - with gr.Row(): - with gr.Column(scale=0.4): - gr.Image("better_banner.jpeg", elem_id="banner-image", show_label=False) - with gr.Column(): - gr.Markdown( - """# Falcon-180B Demo - - **Chat with [Falcon-180B-Chat](https://huggingface.co/tiiuae/falcon-180b-chat), brainstorm ideas, discuss your holiday plans, and more!** - - ✨ This demo is powered by [Falcon-180B](https://huggingface.co/tiiuae/falcon-180B) and finetuned on a mixture of [Ultrachat](https://huggingface.co/datasets/stingning/ultrachat), [Platypus](https://huggingface.co/datasets/garage-bAInd/Open-Platypus) and [Airoboros](https://huggingface.co/datasets/jondurbin/airoboros-2.1). [Falcon-180B](https://huggingface.co/tiiuae/falcon-180b) is a state-of-the-art large language model built by the [Technology Innovation Institute](https://www.tii.ae) in Abu Dhabi. It is trained on 3.5 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the [Falcon-180B TII License](https://huggingface.co/spaces/tiiuae/falcon-180b-license/blob/main/LICENSE.txt). It currently holds the 🥇 1st place on the [🤗 Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) for a pretrained model. - - 🧪 This is only a **first experimental preview**: we intend to provide increasingly capable versions of Falcon in the future, based on improved datasets and RLHF/RLAIF. - - 👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/) - - ➡️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-180B](https://huggingface.co/tiiuae/falcon-180b), to illustrate the impact (and limitations) of finetuning on a dataset of conversations and instructions. We encourage the community to further build upon the base model, and to create even better instruct/chat versions! - - ⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words. - """ - ) - - gr.ChatInterface( - generate, - examples=EXAMPLES, - additional_inputs=additional_inputs, - ) - -demo.queue(concurrency_count=100, api_open=False).launch(show_api=False) diff --git a/spaces/alvanlii/domain-expansion/style_mixing.py b/spaces/alvanlii/domain-expansion/style_mixing.py deleted file mode 100644 index c47bebbc44c0126b6fd00a55b8b487dc7b159653..0000000000000000000000000000000000000000 --- a/spaces/alvanlii/domain-expansion/style_mixing.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -"""Generate style mixing image matrix using pretrained network pickle.""" - -import os -import re -from typing import List - -import click -import dnnlib -import numpy as np -import PIL.Image -import torch - -import legacy - -#---------------------------------------------------------------------------- - -def num_range(s: str) -> List[int]: - '''Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints.''' - - range_re = re.compile(r'^(\d+)-(\d+)$') - m = range_re.match(s) - if m: - return list(range(int(m.group(1)), int(m.group(2))+1)) - vals = s.split(',') - return [int(x) for x in vals] - -#---------------------------------------------------------------------------- - -@click.command() -@click.option('--network', 'network_pkl', help='Network pickle filename', required=True) -@click.option('--rows', 'row_seeds', type=num_range, help='Random seeds to use for image rows', required=True) -@click.option('--cols', 'col_seeds', type=num_range, help='Random seeds to use for image columns', required=True) -@click.option('--styles', 'col_styles', type=num_range, help='Style layer range', default='0-6', show_default=True) -@click.option('--trunc', 'truncation_psi', type=float, help='Truncation psi', default=1, show_default=True) -@click.option('--noise-mode', help='Noise mode', type=click.Choice(['const', 'random', 'none']), default='const', show_default=True) -@click.option('--outdir', type=str, required=True) -def generate_style_mix( - network_pkl: str, - row_seeds: List[int], - col_seeds: List[int], - col_styles: List[int], - truncation_psi: float, - noise_mode: str, - outdir: str -): - """Generate images using pretrained network pickle. - - Examples: - - \b - python style_mixing.py --outdir=out --rows=85,100,75,458,1500 --cols=55,821,1789,293 \\ - --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl - """ - print('Loading networks from "%s"...' % network_pkl) - device = torch.device('cuda') - with dnnlib.util.open_url(network_pkl) as f: - G = legacy.load_network_pkl(f)['G_ema'].to(device) # type: ignore - - os.makedirs(outdir, exist_ok=True) - - print('Generating W vectors...') - all_seeds = list(set(row_seeds + col_seeds)) - all_z = np.stack([np.random.RandomState(seed).randn(G.z_dim) for seed in all_seeds]) - all_w = G.mapping(torch.from_numpy(all_z).to(device), None) - w_avg = G.mapping.w_avg - all_w = w_avg + (all_w - w_avg) * truncation_psi - w_dict = {seed: w for seed, w in zip(all_seeds, list(all_w))} - - print('Generating images...') - all_images = G.synthesis(all_w, noise_mode=noise_mode) - all_images = (all_images.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy() - image_dict = {(seed, seed): image for seed, image in zip(all_seeds, list(all_images))} - - print('Generating style-mixed images...') - for row_seed in row_seeds: - for col_seed in col_seeds: - w = w_dict[row_seed].clone() - w[col_styles] = w_dict[col_seed][col_styles] - image = G.synthesis(w[np.newaxis], noise_mode=noise_mode) - image = (image.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8) - image_dict[(row_seed, col_seed)] = image[0].cpu().numpy() - - print('Saving images...') - os.makedirs(outdir, exist_ok=True) - for (row_seed, col_seed), image in image_dict.items(): - PIL.Image.fromarray(image, 'RGB').save(f'{outdir}/{row_seed}-{col_seed}.png') - - print('Saving image grid...') - W = G.img_resolution - H = G.img_resolution - canvas = PIL.Image.new('RGB', (W * (len(col_seeds) + 1), H * (len(row_seeds) + 1)), 'black') - for row_idx, row_seed in enumerate([0] + row_seeds): - for col_idx, col_seed in enumerate([0] + col_seeds): - if row_idx == 0 and col_idx == 0: - continue - key = (row_seed, col_seed) - if row_idx == 0: - key = (col_seed, col_seed) - if col_idx == 0: - key = (row_seed, row_seed) - canvas.paste(PIL.Image.fromarray(image_dict[key], 'RGB'), (W * col_idx, H * row_idx)) - canvas.save(f'{outdir}/grid.png') - - -#---------------------------------------------------------------------------- - -if __name__ == "__main__": - generate_style_mix() # pylint: disable=no-value-for-parameter - -#---------------------------------------------------------------------------- diff --git a/spaces/amarchheda/ChordDuplicate/portaudio/src/hostapi/skeleton/pa_hostapi_skeleton.c b/spaces/amarchheda/ChordDuplicate/portaudio/src/hostapi/skeleton/pa_hostapi_skeleton.c deleted file mode 100644 index 46808d2f26f97527e78c8e3df48c7381bcf34e1a..0000000000000000000000000000000000000000 --- a/spaces/amarchheda/ChordDuplicate/portaudio/src/hostapi/skeleton/pa_hostapi_skeleton.c +++ /dev/null @@ -1,814 +0,0 @@ -/* - * $Id$ - * Portable Audio I/O Library skeleton implementation - * demonstrates how to use the common functions to implement support - * for a host API - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * 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. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** @file - @ingroup common_src - - @brief Skeleton implementation of support for a host API. - - This file is provided as a starting point for implementing support for - a new host API. It provides examples of how the common code can be used. - - @note IMPLEMENT ME comments are used to indicate functionality - which much be customised for each implementation. -*/ - - -#include /* strlen() */ - -#include "pa_util.h" -#include "pa_allocation.h" -#include "pa_hostapi.h" -#include "pa_stream.h" -#include "pa_cpuload.h" -#include "pa_process.h" - - -/* prototypes for functions declared in this file */ - -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - - -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate ); -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, - PaStream** s, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate, - unsigned long framesPerBuffer, - PaStreamFlags streamFlags, - PaStreamCallback *streamCallback, - void *userData ); -static PaError CloseStream( PaStream* stream ); -static PaError StartStream( PaStream *stream ); -static PaError StopStream( PaStream *stream ); -static PaError AbortStream( PaStream *stream ); -static PaError IsStreamStopped( PaStream *s ); -static PaError IsStreamActive( PaStream *stream ); -static PaTime GetStreamTime( PaStream *stream ); -static double GetStreamCpuLoad( PaStream* stream ); -static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); -static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); -static signed long GetStreamReadAvailable( PaStream* stream ); -static signed long GetStreamWriteAvailable( PaStream* stream ); - - -/* IMPLEMENT ME: a macro like the following one should be used for reporting - host errors */ -#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \ - PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText ) - -/* PaSkeletonHostApiRepresentation - host api datastructure specific to this implementation */ - -typedef struct -{ - PaUtilHostApiRepresentation inheritedHostApiRep; - PaUtilStreamInterface callbackStreamInterface; - PaUtilStreamInterface blockingStreamInterface; - - PaUtilAllocationGroup *allocations; - - /* implementation specific data goes here */ -} -PaSkeletonHostApiRepresentation; /* IMPLEMENT ME: rename this */ - - -PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) -{ - PaError result = paNoError; - int i, deviceCount; - PaSkeletonHostApiRepresentation *skeletonHostApi; - PaDeviceInfo *deviceInfoArray; - - skeletonHostApi = (PaSkeletonHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaSkeletonHostApiRepresentation) ); - if( !skeletonHostApi ) - { - result = paInsufficientMemory; - goto error; - } - - skeletonHostApi->allocations = PaUtil_CreateAllocationGroup(); - if( !skeletonHostApi->allocations ) - { - result = paInsufficientMemory; - goto error; - } - - *hostApi = &skeletonHostApi->inheritedHostApiRep; - (*hostApi)->info.structVersion = 1; - (*hostApi)->info.type = paInDevelopment; /* IMPLEMENT ME: change to correct type id */ - (*hostApi)->info.name = "skeleton implementation"; /* IMPLEMENT ME: change to correct name */ - - (*hostApi)->info.defaultInputDevice = paNoDevice; /* IMPLEMENT ME */ - (*hostApi)->info.defaultOutputDevice = paNoDevice; /* IMPLEMENT ME */ - - (*hostApi)->info.deviceCount = 0; - - deviceCount = 0; /* IMPLEMENT ME */ - - if( deviceCount > 0 ) - { - (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( - skeletonHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount ); - if( !(*hostApi)->deviceInfos ) - { - result = paInsufficientMemory; - goto error; - } - - /* allocate all device info structs in a contiguous block */ - deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( - skeletonHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount ); - if( !deviceInfoArray ) - { - result = paInsufficientMemory; - goto error; - } - - for( i=0; i < deviceCount; ++i ) - { - PaDeviceInfo *deviceInfo = &deviceInfoArray[i]; - deviceInfo->structVersion = 2; - deviceInfo->hostApi = hostApiIndex; - deviceInfo->name = 0; /* IMPLEMENT ME: allocate block and copy name eg: - deviceName = (char*)PaUtil_GroupAllocateMemory( skeletonHostApi->allocations, strlen(srcName) + 1 ); - if( !deviceName ) - { - result = paInsufficientMemory; - goto error; - } - strcpy( deviceName, srcName ); - deviceInfo->name = deviceName; - */ - - deviceInfo->maxInputChannels = 0; /* IMPLEMENT ME */ - deviceInfo->maxOutputChannels = 0; /* IMPLEMENT ME */ - - deviceInfo->defaultLowInputLatency = 0.; /* IMPLEMENT ME */ - deviceInfo->defaultLowOutputLatency = 0.; /* IMPLEMENT ME */ - deviceInfo->defaultHighInputLatency = 0.; /* IMPLEMENT ME */ - deviceInfo->defaultHighOutputLatency = 0.; /* IMPLEMENT ME */ - - deviceInfo->defaultSampleRate = 0.; /* IMPLEMENT ME */ - - (*hostApi)->deviceInfos[i] = deviceInfo; - ++(*hostApi)->info.deviceCount; - } - } - - (*hostApi)->Terminate = Terminate; - (*hostApi)->OpenStream = OpenStream; - (*hostApi)->IsFormatSupported = IsFormatSupported; - - PaUtil_InitializeStreamInterface( &skeletonHostApi->callbackStreamInterface, CloseStream, StartStream, - StopStream, AbortStream, IsStreamStopped, IsStreamActive, - GetStreamTime, GetStreamCpuLoad, - PaUtil_DummyRead, PaUtil_DummyWrite, - PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); - - PaUtil_InitializeStreamInterface( &skeletonHostApi->blockingStreamInterface, CloseStream, StartStream, - StopStream, AbortStream, IsStreamStopped, IsStreamActive, - GetStreamTime, PaUtil_DummyGetCpuLoad, - ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); - - return result; - -error: - if( skeletonHostApi ) - { - if( skeletonHostApi->allocations ) - { - PaUtil_FreeAllAllocations( skeletonHostApi->allocations ); - PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations ); - } - - PaUtil_FreeMemory( skeletonHostApi ); - } - return result; -} - - -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) -{ - PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi; - - /* - IMPLEMENT ME: - - clean up any resources not handled by the allocation group - */ - - if( skeletonHostApi->allocations ) - { - PaUtil_FreeAllAllocations( skeletonHostApi->allocations ); - PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations ); - } - - PaUtil_FreeMemory( skeletonHostApi ); -} - - -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate ) -{ - int inputChannelCount, outputChannelCount; - PaSampleFormat inputSampleFormat, outputSampleFormat; - - if( inputParameters ) - { - inputChannelCount = inputParameters->channelCount; - inputSampleFormat = inputParameters->sampleFormat; - - /* all standard sample formats are supported by the buffer adapter, - this implementation doesn't support any custom sample formats */ - if( inputSampleFormat & paCustomFormat ) - return paSampleFormatNotSupported; - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that input device can support inputChannelCount */ - if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) - return paInvalidChannelCount; - - /* validate inputStreamInfo */ - if( inputParameters->hostApiSpecificStreamInfo ) - return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - } - else - { - inputChannelCount = 0; - } - - if( outputParameters ) - { - outputChannelCount = outputParameters->channelCount; - outputSampleFormat = outputParameters->sampleFormat; - - /* all standard sample formats are supported by the buffer adapter, - this implementation doesn't support any custom sample formats */ - if( outputSampleFormat & paCustomFormat ) - return paSampleFormatNotSupported; - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that output device can support outputChannelCount */ - if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) - return paInvalidChannelCount; - - /* validate outputStreamInfo */ - if( outputParameters->hostApiSpecificStreamInfo ) - return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - } - else - { - outputChannelCount = 0; - } - - /* - IMPLEMENT ME: - - - if a full duplex stream is requested, check that the combination - of input and output parameters is supported if necessary - - - check that the device supports sampleRate - - Because the buffer adapter handles conversion between all standard - sample formats, the following checks are only required if paCustomFormat - is implemented, or under some other unusual conditions. - - - check that input device can support inputSampleFormat, or that - we have the capability to convert from inputSampleFormat to - a native format - - - check that output device can support outputSampleFormat, or that - we have the capability to convert from outputSampleFormat to - a native format - */ - - - /* suppress unused variable warnings */ - (void) sampleRate; - - return paFormatIsSupported; -} - -/* PaSkeletonStream - a stream data structure specifically for this implementation */ - -typedef struct PaSkeletonStream -{ /* IMPLEMENT ME: rename this */ - PaUtilStreamRepresentation streamRepresentation; - PaUtilCpuLoadMeasurer cpuLoadMeasurer; - PaUtilBufferProcessor bufferProcessor; - - /* IMPLEMENT ME: - - implementation specific data goes here - */ - unsigned long framesPerHostCallback; /* just an example */ -} -PaSkeletonStream; - -/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ - -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, - PaStream** s, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate, - unsigned long framesPerBuffer, - PaStreamFlags streamFlags, - PaStreamCallback *streamCallback, - void *userData ) -{ - PaError result = paNoError; - PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi; - PaSkeletonStream *stream = 0; - unsigned long framesPerHostBuffer = framesPerBuffer; /* these may not be equivalent for all implementations */ - int inputChannelCount, outputChannelCount; - PaSampleFormat inputSampleFormat, outputSampleFormat; - PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; - - - if( inputParameters ) - { - inputChannelCount = inputParameters->channelCount; - inputSampleFormat = inputParameters->sampleFormat; - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that input device can support inputChannelCount */ - if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) - return paInvalidChannelCount; - - /* validate inputStreamInfo */ - if( inputParameters->hostApiSpecificStreamInfo ) - return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - - /* IMPLEMENT ME - establish which host formats are available */ - hostInputSampleFormat = - PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat ); - } - else - { - inputChannelCount = 0; - inputSampleFormat = hostInputSampleFormat = paInt16; /* Suppress 'uninitialised var' warnings. */ - } - - if( outputParameters ) - { - outputChannelCount = outputParameters->channelCount; - outputSampleFormat = outputParameters->sampleFormat; - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that output device can support inputChannelCount */ - if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) - return paInvalidChannelCount; - - /* validate outputStreamInfo */ - if( outputParameters->hostApiSpecificStreamInfo ) - return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - - /* IMPLEMENT ME - establish which host formats are available */ - hostOutputSampleFormat = - PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat ); - } - else - { - outputChannelCount = 0; - outputSampleFormat = hostOutputSampleFormat = paInt16; /* Suppress 'uninitialized var' warnings. */ - } - - /* - IMPLEMENT ME: - - ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() FIXME - checks needed? ) - - - check that input device can support inputSampleFormat, or that - we have the capability to convert from outputSampleFormat to - a native format - - - check that output device can support outputSampleFormat, or that - we have the capability to convert from outputSampleFormat to - a native format - - - if a full duplex stream is requested, check that the combination - of input and output parameters is supported - - - check that the device supports sampleRate - - - alter sampleRate to a close allowable rate if possible / necessary - - - validate suggestedInputLatency and suggestedOutputLatency parameters, - use default values where necessary - */ - - - - - /* validate platform specific flags */ - if( (streamFlags & paPlatformSpecificFlags) != 0 ) - return paInvalidFlag; /* unexpected platform specific flag */ - - - stream = (PaSkeletonStream*)PaUtil_AllocateMemory( sizeof(PaSkeletonStream) ); - if( !stream ) - { - result = paInsufficientMemory; - goto error; - } - - if( streamCallback ) - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &skeletonHostApi->callbackStreamInterface, streamCallback, userData ); - } - else - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &skeletonHostApi->blockingStreamInterface, streamCallback, userData ); - } - - PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); - - - /* we assume a fixed host buffer size in this example, but the buffer processor - can also support bounded and unknown host buffer sizes by passing - paUtilBoundedHostBufferSize or paUtilUnknownHostBufferSize instead of - paUtilFixedHostBufferSize below. */ - - result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, - inputChannelCount, inputSampleFormat, hostInputSampleFormat, - outputChannelCount, outputSampleFormat, hostOutputSampleFormat, - sampleRate, streamFlags, framesPerBuffer, - framesPerHostBuffer, paUtilFixedHostBufferSize, - streamCallback, userData ); - if( result != paNoError ) - goto error; - - - /* - IMPLEMENT ME: initialise the following fields with estimated or actual - values. - */ - stream->streamRepresentation.streamInfo.inputLatency = - (PaTime)PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) / sampleRate; /* inputLatency is specified in _seconds_ */ - stream->streamRepresentation.streamInfo.outputLatency = - (PaTime)PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) / sampleRate; /* outputLatency is specified in _seconds_ */ - stream->streamRepresentation.streamInfo.sampleRate = sampleRate; - - - /* - IMPLEMENT ME: - - additional stream setup + opening - */ - - stream->framesPerHostCallback = framesPerHostBuffer; - - *s = (PaStream*)stream; - - return result; - -error: - if( stream ) - PaUtil_FreeMemory( stream ); - - return result; -} - -/* - ExampleHostProcessingLoop() illustrates the kind of processing which may - occur in a host implementation. - -*/ -static void ExampleHostProcessingLoop( void *inputBuffer, void *outputBuffer, void *userData ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)userData; - PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* IMPLEMENT ME */ - int callbackResult; - unsigned long framesProcessed; - - PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); - - /* - IMPLEMENT ME: - - generate timing information - - handle buffer slips - */ - - /* - If you need to byte swap or shift inputBuffer to convert it into a - portaudio format, do it here. - */ - - - - PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */ ); - - /* - depending on whether the host buffers are interleaved, non-interleaved - or a mixture, you will want to call PaUtil_SetInterleaved*Channels(), - PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here. - */ - - PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); - PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, - 0, /* first channel of inputBuffer is channel 0 */ - inputBuffer, - 0 ); /* 0 - use inputChannelCount passed to init buffer processor */ - - PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); - PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, - 0, /* first channel of outputBuffer is channel 0 */ - outputBuffer, - 0 ); /* 0 - use outputChannelCount passed to init buffer processor */ - - /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing() - in general you would pass paContinue for normal operation, and - paComplete to drain the buffer processor's internal output buffer. - You can check whether the buffer processor's output buffer is empty - using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor ) - */ - callbackResult = paContinue; - framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); - - - /* - If you need to byte swap or shift outputBuffer to convert it to - host format, do it here. - */ - - PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); - - - if( callbackResult == paContinue ) - { - /* nothing special to do */ - } - else if( callbackResult == paAbort ) - { - /* IMPLEMENT ME - finish playback immediately */ - - /* once finished, call the finished callback */ - if( stream->streamRepresentation.streamFinishedCallback != 0 ) - stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); - } - else - { - /* User callback has asked us to stop with paComplete or other non-zero value */ - - /* IMPLEMENT ME - finish playback once currently queued audio has completed */ - - /* once finished, call the finished callback */ - if( stream->streamRepresentation.streamFinishedCallback != 0 ) - stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); - } -} - - -/* - When CloseStream() is called, the multi-api layer ensures that - the stream has already been stopped or aborted. -*/ -static PaError CloseStream( PaStream* s ) -{ - PaError result = paNoError; - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* - IMPLEMENT ME: - - additional stream closing + cleanup - */ - - PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); - PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); - PaUtil_FreeMemory( stream ); - - return result; -} - - -static PaError StartStream( PaStream *s ) -{ - PaError result = paNoError; - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); - - /* IMPLEMENT ME, see portaudio.h for required behavior */ - - /* suppress unused function warning. the code in ExampleHostProcessingLoop or - something similar should be implemented to feed samples to and from the - host after StartStream() is called. - */ - (void) ExampleHostProcessingLoop; - - return result; -} - - -static PaError StopStream( PaStream *s ) -{ - PaError result = paNoError; - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior */ - - return result; -} - - -static PaError AbortStream( PaStream *s ) -{ - PaError result = paNoError; - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior */ - - return result; -} - - -static PaError IsStreamStopped( PaStream *s ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior */ - - return 0; -} - - -static PaError IsStreamActive( PaStream *s ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior */ - - return 0; -} - - -static PaTime GetStreamTime( PaStream *s ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior*/ - - return 0; -} - - -static double GetStreamCpuLoad( PaStream* s ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); -} - - -/* - As separate stream interfaces are used for blocking and callback - streams, the following functions can be guaranteed to only be called - for blocking streams. -*/ - -static PaError ReadStream( PaStream* s, - void *buffer, - unsigned long frames ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) buffer; - (void) frames; - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior*/ - - return paNoError; -} - - -static PaError WriteStream( PaStream* s, - const void *buffer, - unsigned long frames ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) buffer; - (void) frames; - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior*/ - - return paNoError; -} - - -static signed long GetStreamReadAvailable( PaStream* s ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior*/ - - return 0; -} - - -static signed long GetStreamWriteAvailable( PaStream* s ) -{ - PaSkeletonStream *stream = (PaSkeletonStream*)s; - - /* suppress unused variable warnings */ - (void) stream; - - /* IMPLEMENT ME, see portaudio.h for required behavior*/ - - return 0; -} diff --git a/spaces/anzorq/hf-spaces-semantic-search/postcss.config.js b/spaces/anzorq/hf-spaces-semantic-search/postcss.config.js deleted file mode 100644 index 33ad091d26d8a9dc95ebdf616e217d985ec215b8..0000000000000000000000000000000000000000 --- a/spaces/anzorq/hf-spaces-semantic-search/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} diff --git a/spaces/apsys/hetfit/intro.md b/spaces/apsys/hetfit/intro.md deleted file mode 100644 index dccb77e40e69829b88a0a65d28329b1d1533ad36..0000000000000000000000000000000000000000 --- a/spaces/apsys/hetfit/intro.md +++ /dev/null @@ -1,453 +0,0 @@ -# :orange[Abstract:] - Hall effect thrusters are one of the most versatile and - popular electric propulsion systems for space use. Industry trends - towards interplanetary missions arise advances in design development - of such propulsion systems. It is understood that correct sizing of - discharge channel in Hall effect thruster impact performance greatly. - Since the complete physics model of such propulsion system is not yet - optimized for fast computations and design iterations, most thrusters - are being designed using so-called scaling laws. But this work focuses - on rather novel approach, which is outlined less frequently than - ordinary scaling design approach in literature. Using deep machine - learning it is possible to create predictive performance model, which - can be used to effortlessly get design of required hall thruster with - required characteristics using way less computing power than design - from scratch and way more flexible than usual scaling approach. -:orange[author:] Korolev K.V [^1] -title: Hall effect thruster design via deep neural network for additive - manufacturing - -# Nomenclature - -
- -$U_d$ = discharge voltage -$P$ = discharge power -$T$ = thrust -$\dot{m}_a$ = mass flow rate -$I_{sp}$ = specific impulse -$\eta_m$ = mass utilization efficiency -$\eta_a$ = anode efficiency -$j$ = $P/v$ \[power density\] -$v$ = discharge channel volume -$h, d, L$ = generic geometry parameters -$C_*$ = set of scaling coefficients -$g$ = free-fall acceleration -$M$ = ion mass - -
- -# Introduction - -The -application of deep learning is extremely diverse, but in this study it -focuses on case of hall effect thruster design. Hall effect thruster -(HET) is rather simple DC plasma acceleration device, due to complex and -non linear process physics we don’t have any full analytical performance -models yet. Though there are a lot of ways these systems are designed in -industry with great efficiencies, but in cost of multi-million research -budgets and time. This problem might be solved using neural network -design approach and few hardware iteration tweaks(Plyashkov et al. -2022-10-25). - -Scaled thrusters tend to have good performance but this approach isn’t -that flexible for numerous reasons: first and foremost, due to large -deviations in all of the initial experimental values accuracy can be not -that good, secondly, it is hardly possible to design thruster with -different power density or $I_{sp}$ efficiently. - -On the other hand, the neural network design approach has accuracy -advantage only on domain of the dataset(Plyashkov et al. 2022-10-25), -this limitations is easily compensated by ability to create relations -between multiple discharge and geometry parameters at once. Hence this -novel approach and scaling relations together could be an ultimate -endgame design tool for HET. - -Note that neither of these models do not include cathode efficiencies -and performances. So as the neutral gas thrust components. Most -correlations in previous literature were made using assumption or -physics laws(Shagayda and Gorshkov 2013-03), in this paper the new -method based on feature generation, GAN dataset augmentation and ML -feature selection is suggested. - -## Dataset enlargement using GAN - -As we already have discussed, the data which is available is not enough -for training NN or most ML algorithms, so I suggest using Generative -Adversarial Network to generate more similar points. Generative model -trains two different models - generator and discriminator. Generator -learns how to generate new points which are classified by discriminator -as similar to real dataset. Of course it is very understandable that -model needs to be precise enough not to overfit on data or create new -unknown correlations. Model was checked via Mean Absolute Percentage -Error (MAPE) and physical boundary conditions. After assembling most -promising architecture, the model was able to generate fake points with -MAPE of $~4.7\%$. We need to measure MAPE to be sure point lie on same -domain as original dataset, as in this work we are interested in -sub-kilowatt thrusters. After model generated new points they were check -to fit in physical boundaries of scaled values (for example thrust -couldn’t be more than 2, efficiency more than 1.4 and so on, data was -scaled on original dataset to retain quality), only 0.02% of points were -found to be outliers. The GAN architecture and dataset sample is -provided as follows. - - - -# General Relations - -As we will use dataset of only low power hall thrusters, we can just -ignore derivation of any non-linear equations and relations and use -traditional approach here. Let’s define some parameters of anode: -$$\alpha = \frac{\dot{m}\beta}{{\dot{m}_a}},$$ -Where $\alpha$ is anode -parameter of $\beta$ thruster parameter. This is selected because this -way cathode and other losses wont be included in the model. One of key -differences in this approach is fitting only best and most appropriate -data, thus we will eliminate some variance in scaling laws. Though due -to machine learning methods, we would need a lot of information which is -simply not available in those volumes. So some simplifications and -assumptions could be made. Firstly, as it was already said, we don’t -include neutralizer efficiency in the model. Secondly, the model would -be correct on very specific domain, defined by dataset, many parameters -like anode power and $I_{sp}$ still are using semi-empirical modelling -approach. The results we are looking for are outputs of machine learning -algorithm: specific impulse, thrust, efficiency, optimal mass flow rate, -power density. Function of input is solely dependant on power and -voltage range. For the matter of topic let’s introduce semi-empirical -equations which are used for scaling current thrusters. - -
- -$$h=C_hd$$ - -$$\dot{m_a} = C_m hd$$ - -$$P_d=C_pU_dd^2$$ - -$$T=C_t\dot{m_a}\sqrt{U_d}$$ - -$$I_{spa}=\frac{T}{\dot{m_a} g}$$ - -$$\eta_a=\frac{T}{2\dot{m_a}P_d}$$ - -
- -Where $C_x$ is scaling coefficient obtained from analytical modelling, -which makes equations linear. Generally it has 95% prediction band but -as was said earlier this linearity is what gives problems to current -thrusters designs (high mass, same power density, average performance). -The original dataset is - -| | | | | | | | | | -|:---------|:---------|:-------|:------|:------|:------|:-------------|:-----|:----------| -| Thruster | Power, W | U_d, V | d, mm | h, mm | L, mm | m_a,.g/s, | T, N | I\_spa, s | -| SPT-20 | 52.4 | 180 | 15.0 | 5.0 | 32.0 | 0.47 | 3.9 | 839 | -| SPT-25 | 134 | 180 | 20.0 | 5.0 | 10 | 0.59 | 5.5 | 948 | -| Music-si | 140 | 288 | 18 | 2 | 6.5 | 0.44 | 4.2 | 850 | -| HET-100 | 174 | 300 | 23.5 | 5.5 | 14.5 | 0.50 | 6.8 | 1386 | -| KHT-40 | 187 | 325 | 31.0 | 9.0 | 25.5 | 0.69 | 10.3 | 1519 | -| KHT-50 | 193 | 250 | 42.0 | 8.0 | 25.0 | 0.88 | 11.6 | 1339 | -| HEPS-200 | 195 | 250 | 42.5 | 8.5 | 25.0 | 0.88 | 11.2 | 1300 | -| BHT-200 | 200 | 250 | 21.0 | 5.6 | 11.2 | 0.94 | 12.8 | 1390 | -| KM-32 | 215 | 250 | 32.0 | 7.0 | 16.0 | 1.00 | 12.2 | 1244 | -| ... | | | | | | | | | -| HEPS-500 | 482 | 300 | 49.5 | 15.5 | 25.0 | 1.67 | 25.9 | 1587 | -| UAH-78AM | 520 | 260 | 78.0 | 20 | 40 | 2 | 30 | 1450 | -| BHT-600 | 615 | 300 | 56.0 | 16.0 | 32 | 2.60 | 39.1 | 1530 | -| SPT-70 | 660 | 300 | 56.0 | 14.0 | 25.0 | 2.56 | 40.0 | 1593 | -| MaSMi60 | 700 | 250 | 60 | 9.42 | 19 | 2.56 | 30 | 1300 | -| MaSMiDm | 1000 | 500 | 67 | 10.5 | 21 | 3 | 53 | 1940 | -| SPT-100 | 1350 | 300 | 85.0 | 15.0 | 25.0 | 5.14 | 81.6 | 1540 | - -Hosting only 24 entries in total. The references are as follows(Beal et -al. 2004-11)(Belikov et al. 2001-07-08)(Kronhaus et al. 2013-07)(Misuri -and Andrenucci 2008-07-21)(Lee et al. 2019-11) - -In the next section the used neural networks architectures will be -discussed. - -# Data driven HET designs - -Neural networks are a type of machine learning algorithm that is often -used in the field of artificial intelligence. They are mathematical -models that can be trained to recognize patterns within large datasets. -The architecture of GAN’s generator was already shown. In this section -we will focus on fully connected networks, which are most popular for -type for these tasks. HETFit code leverages dynamic architecture -generation of these FcNN’s which is done via meta learning algorithm -Tree-structured Parzen Estimator for every data input user selects. This -code uses state-of-art implementation made by OPTUNA. The dynamically -suggested architecture has 2 to 6 layers from 4 to 128 nodes on each -with SELU, Tanh or ReLU activations and most optimal optimizer. The code -user interface is as follows: 1. Specify working environment 2. Load or -generate data 3. Tune the architecture 4. Train and get robust scaling -models - -## FNN - -All of Fully connected neural networks are implemented in PyTorch as it -the most powerful ML/AI library for experiments. When the network -architecture is generated, all of networks have similar training loops -as they use gradient descend algorithm : Loss function: -$$L(w, b) \equiv \frac{1}{2 n} \sum_x\|y(x)-a\|^2$$ This one is mean -square error (MSE) error function most commonly used in FNNs. Next we -iterate while updating weights for a number of specified epochs this -way. Loop for number of epochs: - -\- Get predictions: $\hat{y}$ - -\- Compute loss: $\mathscr{L}(w, b)$ - -\- Make backward pass - -\- Update optimizer - -It can be mentioned that dataset of electric propulsion is extremely -complex due to large deviations in data. Thanks to adavnces in data -science and ML it is possible to work with it. - -This way we assembled dataset on our ROI domain of $P$\<1000 $W$ input -power and 200-500 $V$ range. Sadly one of limitations of such model is -disability to go beyond actual database limit while not sacrificing -performance and accuracy. - -## Physics Informed Neural Networks - -For working with unscaled data PINN’s were introduced, they are using -equations 2-7 to generate $C_x$ coefficients. Yes, it was said earlier -that this method lacks ability to generate better performing HETs, but -as we have generated larger dataset on same domain as Lee et al. -(2019-11) it is important to control that our dataset is still the same -quality as original. Using above mentioned PINN’s it was possible to fit -coefficients and they showed only slight divergence in values of few % -which is acceptable. - -## ML approach notes - -We already have discussed how HETFit code works and results it can -generate, the overiew is going to be given in next section. But here i -want to warn that this work is highly experimental and you should always -take ML approaches with a grain of salt, as some plasma discharge -physics in HET is yet to be understood, data driven way may have some -errors in predictions on specific bands. Few notes on design tool I have -developed in this work: it is meant to be used by people with little to -no experience in ML field but those who wants to quickly analyze their -designs or create baseline one for simulations. One can even use this -tool for general tabular data as it has mostly no limits whatsoever to -input data. - -## Two input variables prediction - -One of main characteristics for any type of thruster is efficiency, in -this work I researched dependency of multiple input values to $\eta_t$. -Results are as follows in form of predicted matrix visualisations. -Figure 3 takes into account all previous ones in the same time, once -again it would be way harder to do without ML. - - - -# Results discussion - -Let’s compare predictions of semi empirical approach(Lee et al. -2019-11), approach in paper(Plyashkov et al. 2022-10-25), and finally -ours. Worth to mention that current approach is easiest to redesign from -scratch. - -## NN architecture generation algorithm - -As with 50 iterations, previously discussed meta learning model is able -to create architecture with score of 0.9+ in matter of seconds. HETFit -allows logging into neptune.ai environment for full control over -simulations. Example trail run looks like that. - - - -## Power density and magnetic flux dependence - -Neither of the models currently support taking magnetic flux in account -besides general physics relations, but we are planning on updating the -model in next follow up paper. For now $\vec{B}$ relation to power -remains unresolved to ML approach but the magnetic field distribution on -z axis is computable and looks like that for magnetically shielded -thrusters: - - - -## Dependency of T on d,P - -Following graph is describing Thrust as function of channel diameter and -width, where hue map is thrust. It is well known dependency and it has -few around 95% prediction band (Lee et al. 2019-11) - - - -## Dependency of T on P,U - - - -## Dependency of T on $m_a$,P - -Compared to(Shagayda and Gorshkov 2013-03) The model accounts for more -parameters than linear relation. So such method proves to be more -precise on specified domain than semi empirical linear relations. - - - -## Dependency of $I_{sp}$ on d,h - - - -We generated many models so far, but using ML we can make single model -for all of the parameters at the same time, so these graphs tend to be -3d projection of such model inference. - -## Use of pretrained model in additive manufacturing of hall effect thruster channels - -The above mentioned model was used to predict geometry of channel, next -the simulation was conducted on this channel. Second one for comparison -was calculated via usual scaling laws. The initial conditions for both -are: - -| Initial condition | Value | -|:------------------|:------------------| -| $n_{e,0}$ | 1e13 \[m\^-3\] | -| $\epsilon_0$ | 4 \[V\] | -| V | 300 \[V\] | -| T | 293.15 \[K\] | -| P\_abs | 0.5 \[torr\] | -| $\mu_e N_n$ | 1e25 \[1/(Vm s)\] | -| dt | 1e-8 \[s\] | -| Body | Ar | - -Outcomes are so that ML geometry results in higher density generation of -ions which leads to more efficient thrust generation. HETFit code -suggests HET parameters by lower estimate to compensate for not included -variables in model of HET. This is experimentally proven to be efficient -estimate since SEM predictions of thrust are always higher than real -performance. Lee et al. (2019-11) - - - -## Code description - -Main concepts: - Each observational/design session is called an -environment, for now it can be either RCI or SCI (Real or scaled -interface) - -\- Most of the run parameters are specified on this object -initialization, including generation of new samples via GAN - -\- Built-in feature generation (log10 Power, efficiency, $\vec{B}$, -etc.) - -\- Top feature selection for each case. (Boruta algorithm) - -\- Compilation of environment with model of choice, can be any torch -model or sklearn one - -\- Training - -\- Plot, inference, save, export to jit/onnx, measure performance - -## COMSOL HET simulations - -The simulations were conducted in COMSOL in plasma physics interface -which gives the ability to accurately compute Electron densities, -temperatures, energy distribution functions from initial conditions and -geometry. Here is comparison of both channels. - - - -# Conclusion - -In conclusion the another model of scaling laws was made and presented. -HETFit code is open source and free to be used by anyone. Additively -manufactured channel was printed to prove it’s manufactureability. -Hopefully this work will help developing more modern scaling relations -as current ones are far from perfect. - -Method in this paper and firstly used in Plyashkov et al. (2022-10-25) -has advantages over SEM one in: ability to preidct performance more -precisely on given domain, account for experimental data. I believe with -more input data the ML method of deisgning thrusters would be more -widely used. - -The code in this work could be used with other tabular experimental data -since most of cases and tasks tend to be the same: feature selection and -model optimization. - - -
- -
- -Beal, Brian E., Alec D. Gallimore, James M. Haas, and William A. Hargus. -2004-11. “Plasma Properties in the Plume of a Hall Thruster Cluster.” -*Journal of Propulsion and Power* 20 (6): 985–91. -. - -
- -
- -Belikov, M., O. Gorshkov, V. Muravlev, R. Rizakhanov, A. Shagayda, and -A. Snnirev. 2001-07-08. “High-Performance Low Power Hall Thruster.” In -*37th Joint Propulsion Conference and Exhibit*. Salt Lake -City,UT,U.S.A.: American Institute of Aeronautics; Astronautics. -. - -
- -
- -Kronhaus, Igal, Alexander Kapulkin, Vladimir Balabanov, Maksim -Rubanovich, Moshe Guelman, and Benveniste Natan. 2013-07. “Discharge -Characterization of the Coaxial Magnetoisolated Longitudinal Anode Hall -Thruster.” *Journal of Propulsion and Power* 29 (4): 938–49. -. - -
- -
- -Lee, Eunkwang, Younho Kim, Hodong Lee, Holak Kim, Guentae Doh, Dongho -Lee, and Wonho Choe. 2019-11. “Scaling Approach for Sub-Kilowatt -Hall-Effect Thrusters.” *Journal of Propulsion and Power* 35 (6): -1073–79. . - -
- -
- -Misuri, Tommaso, and Mariano Andrenucci. 2008-07-21. “HET Scaling -Methodology: Improvement and Assessment.” In *44th AIAA/ASME/SAE/ASEE -Joint Propulsion Conference &Amp; Exhibit*. Hartford, CT: American -Institute of Aeronautics; Astronautics. -. - -
- -
- -Plyashkov, Yegor V., Andrey A. Shagayda, Dmitrii A. Kravchenko, Fedor D. -Ratnikov, and Alexander S. Lovtsov. 2022-10-25. “On Scaling of -Hall-Effect Thrusters Using Neural Nets,” 2022-10-25. -. - -
- -
- -Shagayda, Andrey A., and Oleg A. Gorshkov. 2013-03. “Hall-Thruster -Scaling Laws.” *Journal of Propulsion and Power* 29 (2): 466–74. -. - -
- -
- -[^1]: Founder, Pure EP \ No newline at end of file diff --git a/spaces/artificialguybr/pixel-art-generator/image_processing.py b/spaces/artificialguybr/pixel-art-generator/image_processing.py deleted file mode 100644 index 0dcad7d5c9d87d933a02202cdd532acdd6f689ec..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/pixel-art-generator/image_processing.py +++ /dev/null @@ -1,69 +0,0 @@ -from PIL import Image - -DITHER_METHODS = { - "None": Image.Dither.NONE, - "Floyd-Steinberg": Image.Dither.FLOYDSTEINBERG -} - -QUANTIZATION_METHODS = { - "Median cut": Image.Quantize.MEDIANCUT, - "Maximum coverage": Image.Quantize.MAXCOVERAGE, - "Fast octree": Image.Quantize.FASTOCTREE, - "libimagequant": Image.Quantize.LIBIMAGEQUANT -} - - -def downscale_image(image: Image, scale: int) -> Image: - width, height = image.size - downscaled_image = image.resize((int(width / scale), int(height / scale)), Image.NEAREST) - return downscaled_image - -def limit_colors( - image, - limit: int=16, - palette=None, - palette_colors: int=256, - quantize: Image.Quantize=Image.Quantize.MEDIANCUT, - dither: Image.Dither=Image.Dither.NONE, - use_k_means: bool=False - ): - if use_k_means: - k_means_value = limit - else: - k_means_value = 0 - - if palette: - palette_image = palette - ppalette = palette.getcolors() - if ppalette: - color_palette = palette.quantize(colors=len(list(set(ppalette)))) - else: - colors = len(palette_image.getcolors()) if palette_image.getcolors() else palette_colors - color_palette = palette_image.quantize(colors, kmeans=colors) - else: - # we need to get palette from image, because - # dither in quantize doesn't work without it - # https://pillow.readthedocs.io/en/stable/_modules/PIL/Image.html#Image.quantize - color_palette = image.quantize(colors=limit, kmeans=k_means_value, method=quantize, dither=Image.Dither.NONE) - - new_image = image.quantize(palette=color_palette, dither=dither) - - return new_image - -def convert_to_grayscale(image): - new_image = image.convert("L") - return new_image.convert("RGB") - -def convert_to_black_and_white(image: Image, threshold: int=128, is_inversed: bool=False): - if is_inversed: - apply_threshold = lambda x : 255 if x < threshold else 0 - else: - apply_threshold = lambda x : 255 if x > threshold else 0 - - black_and_white_image = image.convert('L', dither=Image.Dither.NONE).point(apply_threshold, mode='1') - return black_and_white_image.convert("RGB") - -def resize_image(image: Image, size) -> Image: - width, height = size - resized_image = image.resize((width, height), Image.NEAREST) - return resized_image \ No newline at end of file diff --git a/spaces/arxify/RVC-beta-v2-0618/MDXNet.py b/spaces/arxify/RVC-beta-v2-0618/MDXNet.py deleted file mode 100644 index 99780afb2266a058a172e13c74e63c92b115e8c2..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/MDXNet.py +++ /dev/null @@ -1,274 +0,0 @@ -import soundfile as sf -import torch, pdb, time, argparse, os, warnings, sys, librosa -import numpy as np -import onnxruntime as ort -from scipy.io.wavfile import write -from tqdm import tqdm -import torch -import torch.nn as nn - -dim_c = 4 - - -class Conv_TDF_net_trim: - def __init__( - self, device, model_name, target_name, L, dim_f, dim_t, n_fft, hop=1024 - ): - super(Conv_TDF_net_trim, self).__init__() - - self.dim_f = dim_f - self.dim_t = 2**dim_t - self.n_fft = n_fft - self.hop = hop - self.n_bins = self.n_fft // 2 + 1 - self.chunk_size = hop * (self.dim_t - 1) - self.window = torch.hann_window(window_length=self.n_fft, periodic=True).to( - device - ) - self.target_name = target_name - self.blender = "blender" in model_name - - out_c = dim_c * 4 if target_name == "*" else dim_c - self.freq_pad = torch.zeros( - [1, out_c, self.n_bins - self.dim_f, self.dim_t] - ).to(device) - - self.n = L // 2 - - def stft(self, x): - x = x.reshape([-1, self.chunk_size]) - x = torch.stft( - x, - n_fft=self.n_fft, - hop_length=self.hop, - window=self.window, - center=True, - return_complex=True, - ) - x = torch.view_as_real(x) - x = x.permute([0, 3, 1, 2]) - x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape( - [-1, dim_c, self.n_bins, self.dim_t] - ) - return x[:, :, : self.dim_f] - - def istft(self, x, freq_pad=None): - freq_pad = ( - self.freq_pad.repeat([x.shape[0], 1, 1, 1]) - if freq_pad is None - else freq_pad - ) - x = torch.cat([x, freq_pad], -2) - c = 4 * 2 if self.target_name == "*" else 2 - x = x.reshape([-1, c, 2, self.n_bins, self.dim_t]).reshape( - [-1, 2, self.n_bins, self.dim_t] - ) - x = x.permute([0, 2, 3, 1]) - x = x.contiguous() - x = torch.view_as_complex(x) - x = torch.istft( - x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True - ) - return x.reshape([-1, c, self.chunk_size]) - - -def get_models(device, dim_f, dim_t, n_fft): - return Conv_TDF_net_trim( - device=device, - model_name="Conv-TDF", - target_name="vocals", - L=11, - dim_f=dim_f, - dim_t=dim_t, - n_fft=n_fft, - ) - - -warnings.filterwarnings("ignore") -cpu = torch.device("cpu") -if torch.cuda.is_available(): - device = torch.device("cuda:0") -elif torch.backends.mps.is_available(): - device = torch.device("mps") -else: - device = torch.device("cpu") - - -class Predictor: - def __init__(self, args): - self.args = args - self.model_ = get_models( - device=cpu, dim_f=args.dim_f, dim_t=args.dim_t, n_fft=args.n_fft - ) - self.model = ort.InferenceSession( - os.path.join(args.onnx, self.model_.target_name + ".onnx"), - providers=["CUDAExecutionProvider", "CPUExecutionProvider"], - ) - print("onnx load done") - - def demix(self, mix): - samples = mix.shape[-1] - margin = self.args.margin - chunk_size = self.args.chunks * 44100 - assert not margin == 0, "margin cannot be zero!" - if margin > chunk_size: - margin = chunk_size - - segmented_mix = {} - - if self.args.chunks == 0 or samples < chunk_size: - chunk_size = samples - - counter = -1 - for skip in range(0, samples, chunk_size): - counter += 1 - - s_margin = 0 if counter == 0 else margin - end = min(skip + chunk_size + margin, samples) - - start = skip - s_margin - - segmented_mix[skip] = mix[:, start:end].copy() - if end == samples: - break - - sources = self.demix_base(segmented_mix, margin_size=margin) - """ - mix:(2,big_sample) - segmented_mix:offset->(2,small_sample) - sources:(1,2,big_sample) - """ - return sources - - def demix_base(self, mixes, margin_size): - chunked_sources = [] - progress_bar = tqdm(total=len(mixes)) - progress_bar.set_description("Processing") - for mix in mixes: - cmix = mixes[mix] - sources = [] - n_sample = cmix.shape[1] - model = self.model_ - trim = model.n_fft // 2 - gen_size = model.chunk_size - 2 * trim - pad = gen_size - n_sample % gen_size - mix_p = np.concatenate( - (np.zeros((2, trim)), cmix, np.zeros((2, pad)), np.zeros((2, trim))), 1 - ) - mix_waves = [] - i = 0 - while i < n_sample + pad: - waves = np.array(mix_p[:, i : i + model.chunk_size]) - mix_waves.append(waves) - i += gen_size - mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(cpu) - with torch.no_grad(): - _ort = self.model - spek = model.stft(mix_waves) - if self.args.denoise: - spec_pred = ( - -_ort.run(None, {"input": -spek.cpu().numpy()})[0] * 0.5 - + _ort.run(None, {"input": spek.cpu().numpy()})[0] * 0.5 - ) - tar_waves = model.istft(torch.tensor(spec_pred)) - else: - tar_waves = model.istft( - torch.tensor(_ort.run(None, {"input": spek.cpu().numpy()})[0]) - ) - tar_signal = ( - tar_waves[:, :, trim:-trim] - .transpose(0, 1) - .reshape(2, -1) - .numpy()[:, :-pad] - ) - - start = 0 if mix == 0 else margin_size - end = None if mix == list(mixes.keys())[::-1][0] else -margin_size - if margin_size == 0: - end = None - sources.append(tar_signal[:, start:end]) - - progress_bar.update(1) - - chunked_sources.append(sources) - _sources = np.concatenate(chunked_sources, axis=-1) - # del self.model - progress_bar.close() - return _sources - - def prediction(self, m, vocal_root, others_root, format): - os.makedirs(vocal_root, exist_ok=True) - os.makedirs(others_root, exist_ok=True) - basename = os.path.basename(m) - mix, rate = librosa.load(m, mono=False, sr=44100) - if mix.ndim == 1: - mix = np.asfortranarray([mix, mix]) - mix = mix.T - sources = self.demix(mix.T) - opt = sources[0].T - if format in ["wav", "flac"]: - sf.write( - "%s/%s_main_vocal.%s" % (vocal_root, basename, format), mix - opt, rate - ) - sf.write("%s/%s_others.%s" % (others_root, basename, format), opt, rate) - else: - path_vocal = "%s/%s_main_vocal.wav" % (vocal_root, basename) - path_other = "%s/%s_others.wav" % (others_root, basename) - sf.write(path_vocal, mix - opt, rate) - sf.write(path_other, opt, rate) - if os.path.exists(path_vocal): - os.system( - "ffmpeg -i %s -vn %s -q:a 2 -y" - % (path_vocal, path_vocal[:-4] + ".%s" % format) - ) - if os.path.exists(path_other): - os.system( - "ffmpeg -i %s -vn %s -q:a 2 -y" - % (path_other, path_other[:-4] + ".%s" % format) - ) - - -class MDXNetDereverb: - def __init__(self, chunks): - self.onnx = "uvr5_weights/onnx_dereverb_By_FoxJoy" - self.shifts = 10 #'Predict with randomised equivariant stabilisation' - self.mixing = "min_mag" # ['default','min_mag','max_mag'] - self.chunks = chunks - self.margin = 44100 - self.dim_t = 9 - self.dim_f = 3072 - self.n_fft = 6144 - self.denoise = True - self.pred = Predictor(self) - - def _path_audio_(self, input, vocal_root, others_root, format): - self.pred.prediction(input, vocal_root, others_root, format) - - -if __name__ == "__main__": - dereverb = MDXNetDereverb(15) - from time import time as ttime - - t0 = ttime() - dereverb._path_audio_( - "雪雪伴奏对消HP5.wav", - "vocal", - "others", - ) - t1 = ttime() - print(t1 - t0) - - -""" - -runtime\python.exe MDXNet.py - -6G: -15/9:0.8G->6.8G -14:0.8G->6.5G -25:炸 - -half15:0.7G->6.6G,22.69s -fp32-15:0.7G->6.6G,20.85s - -""" diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/vegalite/v4/schema/core.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/vegalite/v4/schema/core.py deleted file mode 100644 index acb88bed8e34916d1936177a2c44b4db7209f3e2..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/vegalite/v4/schema/core.py +++ /dev/null @@ -1,19905 +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:`TopLevelNormalizedConcatSpecGenericSpec`, - :class:`TopLevelNormalizedVConcatSpecGenericSpec`, - :class:`TopLevelNormalizedHConcatSpecGenericSpec`) - 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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - 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`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - tension : anyOf(float, :class:`ExprRef`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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. - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, timeUnitBand=Undefined, timeUnitBandPosition=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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, tooltip=tooltip, - url=url, width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class ArgmaxDef(Aggregate): - """ArgmaxDef schema wrapper - - Mapping(required=[argmax]) - - Attributes - ---------- - - argmax : string - - """ - _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]) - - Attributes - ---------- - - argmin : string - - """ - _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=[]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - - bandPosition : anyOf(float, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - domain : anyOf(boolean, :class:`ExprRef`) - - domainCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - - domainColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - domainDash : anyOf(List(float), :class:`ExprRef`) - - domainDashOffset : anyOf(float, :class:`ExprRef`) - - domainOpacity : anyOf(float, :class:`ExprRef`) - - domainWidth : anyOf(float, :class:`ExprRef`) - - format : anyOf(string, :class:`Dictunknown`) - 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`) - - gridColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, - :class:`ConditionalAxisColor`) - - gridDash : anyOf(List(float), :class:`ExprRef`, :class:`ConditionalAxisNumberArray`) - - gridDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - gridOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - gridWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`, :class:`ConditionalAxisLabelAlign`) - - labelAngle : anyOf(float, :class:`ExprRef`) - - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`, - :class:`ConditionalAxisLabelBaseline`) - - labelBound : anyOf(anyOf(float, boolean), :class:`ExprRef`) - - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, - :class:`ConditionalAxisColor`) - - 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`) - - labelFont : anyOf(string, :class:`ExprRef`, :class:`ConditionalAxisString`) - - labelFontSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`, - :class:`ConditionalAxisLabelFontStyle`) - - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`, - :class:`ConditionalAxisLabelFontWeight`) - - labelLimit : anyOf(float, :class:`ExprRef`) - - labelLineHeight : anyOf(float, :class:`ExprRef`) - - labelOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - labelOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - 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`) - - labelSeparation : anyOf(float, :class:`ExprRef`) - - labels : anyOf(boolean, :class:`ExprRef`) - - maxExtent : anyOf(float, :class:`ExprRef`) - - minExtent : anyOf(float, :class:`ExprRef`) - - offset : float - 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`) - - tickCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - - tickColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, - :class:`ConditionalAxisColor`) - - 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`) - - tickDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - tickExtra : anyOf(boolean, :class:`ExprRef`) - - 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`) - - tickOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - tickRound : anyOf(boolean, :class:`ExprRef`) - - tickSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - tickWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - ticks : anyOf(boolean, :class:`ExprRef`) - - 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`) - - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - - titleAngle : anyOf(float, :class:`ExprRef`) - - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - titleFont : anyOf(string, :class:`ExprRef`) - - titleFontSize : anyOf(float, :class:`ExprRef`) - - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - titleLimit : anyOf(float, :class:`ExprRef`) - - titleLineHeight : anyOf(float, :class:`ExprRef`) - - titleOpacity : anyOf(float, :class:`ExprRef`) - - titlePadding : anyOf(float, :class:`ExprRef`) - - titleX : anyOf(float, :class:`ExprRef`) - - titleY : anyOf(float, :class:`ExprRef`) - - translate : anyOf(float, :class:`ExprRef`) - - 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=[]) - - Attributes - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - - bandPosition : anyOf(float, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - disable : boolean - Disable axis by default. - domain : anyOf(boolean, :class:`ExprRef`) - - domainCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - - domainColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - domainDash : anyOf(List(float), :class:`ExprRef`) - - domainDashOffset : anyOf(float, :class:`ExprRef`) - - domainOpacity : anyOf(float, :class:`ExprRef`) - - domainWidth : anyOf(float, :class:`ExprRef`) - - format : anyOf(string, :class:`Dictunknown`) - 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`) - - gridColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, - :class:`ConditionalAxisColor`) - - gridDash : anyOf(List(float), :class:`ExprRef`, :class:`ConditionalAxisNumberArray`) - - gridDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - gridOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - gridWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`, :class:`ConditionalAxisLabelAlign`) - - labelAngle : anyOf(float, :class:`ExprRef`) - - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`, - :class:`ConditionalAxisLabelBaseline`) - - labelBound : anyOf(anyOf(float, boolean), :class:`ExprRef`) - - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, - :class:`ConditionalAxisColor`) - - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **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`) - - labelFont : anyOf(string, :class:`ExprRef`, :class:`ConditionalAxisString`) - - labelFontSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`, - :class:`ConditionalAxisLabelFontStyle`) - - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`, - :class:`ConditionalAxisLabelFontWeight`) - - labelLimit : anyOf(float, :class:`ExprRef`) - - labelLineHeight : anyOf(float, :class:`ExprRef`) - - labelOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - labelOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - 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`) - - labelSeparation : anyOf(float, :class:`ExprRef`) - - labels : anyOf(boolean, :class:`ExprRef`) - - maxExtent : anyOf(float, :class:`ExprRef`) - - minExtent : anyOf(float, :class:`ExprRef`) - - offset : float - 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`) - - tickCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - - tickColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, - :class:`ConditionalAxisColor`) - - 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`) - - tickDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - tickExtra : anyOf(boolean, :class:`ExprRef`) - - 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`) - - tickOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - tickRound : anyOf(boolean, :class:`ExprRef`) - - tickSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - tickWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - - ticks : anyOf(boolean, :class:`ExprRef`) - - 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`) - - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - - titleAngle : anyOf(float, :class:`ExprRef`) - - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - titleFont : anyOf(string, :class:`ExprRef`) - - titleFontSize : anyOf(float, :class:`ExprRef`) - - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - titleLimit : anyOf(float, :class:`ExprRef`) - - titleLineHeight : anyOf(float, :class:`ExprRef`) - - titleOpacity : anyOf(float, :class:`ExprRef`) - - titlePadding : anyOf(float, :class:`ExprRef`) - - titleX : anyOf(float, :class:`ExprRef`) - - titleY : anyOf(float, :class:`ExprRef`) - - translate : anyOf(float, :class:`ExprRef`) - - 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=[]) - - Attributes - ---------- - - 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 BarConfig(AnyMarkConfig): - """BarConfig schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - 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`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - discreteBandSize : float - 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`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - lineBreak : anyOf(string, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - tension : anyOf(float, :class:`ExprRef`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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. - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, - timeUnitBand=Undefined, timeUnitBandPosition=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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, tooltip=tooltip, - url=url, width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class BaseTitleNoValueRefs(VegaLiteSchema): - """BaseTitleNoValueRefs schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - align : :class:`Align` - Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or - ``"right"``. - anchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - - angle : anyOf(float, :class:`ExprRef`) - - aria : anyOf(boolean, :class:`ExprRef`) - - 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`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - font : anyOf(string, :class:`ExprRef`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - frame : anyOf(anyOf(:class:`TitleFrame`, string), :class:`ExprRef`) - - limit : anyOf(float, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - offset : anyOf(float, :class:`ExprRef`) - - orient : anyOf(:class:`TitleOrient`, :class:`ExprRef`) - - subtitleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - subtitleFont : anyOf(string, :class:`ExprRef`) - - subtitleFontSize : anyOf(float, :class:`ExprRef`) - - subtitleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - subtitleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - subtitleLineHeight : anyOf(float, :class:`ExprRef`) - - subtitlePadding : anyOf(float, :class:`ExprRef`) - - zindex : anyOf(float, :class:`ExprRef`) - - """ - _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, float]), :class:`SelectionExtent`) - """ - _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. - - Attributes - ---------- - - 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, 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:`InputBinding`) - """ - _schema = {'$ref': '#/definitions/Binding'} - - def __init__(self, *args, **kwds): - super(Binding, self).__init__(*args, **kwds) - - -class BindCheckbox(Binding): - """BindCheckbox schema wrapper - - Mapping(required=[input]) - - Attributes - ---------- - - input : string - - debounce : float - - element : :class:`Element` - - name : string - - type : string - - """ - _schema = {'$ref': '#/definitions/BindCheckbox'} - - def __init__(self, input=Undefined, debounce=Undefined, element=Undefined, name=Undefined, - type=Undefined, **kwds): - super(BindCheckbox, self).__init__(input=input, debounce=debounce, element=element, name=name, - type=type, **kwds) - - -class BindRadioSelect(Binding): - """BindRadioSelect schema wrapper - - Mapping(required=[input, options]) - - Attributes - ---------- - - input : enum('radio', 'select') - - options : List(Any) - - debounce : float - - element : :class:`Element` - - labels : List(string) - - name : string - - type : string - - """ - _schema = {'$ref': '#/definitions/BindRadioSelect'} - - def __init__(self, input=Undefined, options=Undefined, debounce=Undefined, element=Undefined, - labels=Undefined, name=Undefined, type=Undefined, **kwds): - super(BindRadioSelect, self).__init__(input=input, options=options, debounce=debounce, - element=element, labels=labels, name=name, type=type, - **kwds) - - -class BindRange(Binding): - """BindRange schema wrapper - - Mapping(required=[input]) - - Attributes - ---------- - - input : string - - debounce : float - - element : :class:`Element` - - max : float - - min : float - - name : string - - step : float - - type : string - - """ - _schema = {'$ref': '#/definitions/BindRange'} - - def __init__(self, input=Undefined, debounce=Undefined, element=Undefined, max=Undefined, - min=Undefined, name=Undefined, step=Undefined, type=Undefined, **kwds): - super(BindRange, self).__init__(input=input, debounce=debounce, element=element, max=max, - min=min, name=name, step=step, type=type, **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=[]) - - Attributes - ---------- - - box : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - 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:`MarkConfigExprOrSignalRef`) - - outliers : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - rule : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - size : float - Size of the box and median tick of a box plot - ticks : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - """ - _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=[]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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:`MarkConfigExprOrSignalRef`) - - 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``. - median : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - 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:`MarkConfigExprOrSignalRef`) - - rule : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - size : float - Size of the box and median tick of a box plot - ticks : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - """ - _schema = {'$ref': '#/definitions/BoxPlotDef'} - - def __init__(self, type=Undefined, box=Undefined, clip=Undefined, color=Undefined, extent=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, - median=median, opacity=opacity, orient=orient, - outliers=outliers, rule=rule, size=size, ticks=ticks, **kwds) - - -class CompositionConfig(VegaLiteSchema): - """CompositionConfig schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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:`ConditionalSelectionMarkPropFieldOrDatumDef`) - """ - _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:`ConditionalSelectionMarkPropFieldOrDatumDefTypeForShape`) - """ - _schema = {'$ref': '#/definitions/ConditionalMarkPropFieldOrDatumDef'} - - def __init__(self, *args, **kwds): - super(ConditionalMarkPropFieldOrDatumDefTypeForShape, 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 ConditionalSelectionMarkPropFieldOrDatumDef(ConditionalMarkPropFieldOrDatumDef): - """ConditionalSelectionMarkPropFieldOrDatumDef schema wrapper - - anyOf(Mapping(required=[selection]), Mapping(required=[selection])) - """ - _schema = {'$ref': '#/definitions/ConditionalSelection'} - - def __init__(self, *args, **kwds): - super(ConditionalSelectionMarkPropFieldOrDatumDef, self).__init__(*args, **kwds) - - -class ConditionalSelectionMarkPropFieldOrDatumDefTypeForShape(ConditionalMarkPropFieldOrDatumDefTypeForShape): - """ConditionalSelectionMarkPropFieldOrDatumDefTypeForShape schema wrapper - - anyOf(Mapping(required=[selection]), Mapping(required=[selection])) - """ - _schema = {'$ref': '#/definitions/ConditionalSelection>'} - - def __init__(self, *args, **kwds): - super(ConditionalSelectionMarkPropFieldOrDatumDefTypeForShape, self).__init__(*args, **kwds) - - -class ConditionalStringFieldDef(VegaLiteSchema): - """ConditionalStringFieldDef schema wrapper - - anyOf(:class:`ConditionalPredicateStringFieldDef`, - :class:`ConditionalSelectionStringFieldDef`) - """ - _schema = {'$ref': '#/definitions/ConditionalStringFieldDef'} - - def __init__(self, *args, **kwds): - super(ConditionalStringFieldDef, self).__init__(*args, **kwds) - - -class ConditionalPredicateStringFieldDef(ConditionalStringFieldDef): - """ConditionalPredicateStringFieldDef schema wrapper - - Mapping(required=[test]) - - Attributes - ---------- - - 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. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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, band=Undefined, bin=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, labelExpr=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(ConditionalPredicateStringFieldDef, self).__init__(test=test, aggregate=aggregate, - band=band, bin=bin, field=field, - format=format, formatType=formatType, - labelExpr=labelExpr, timeUnit=timeUnit, - title=title, type=type, **kwds) - - -class ConditionalSelectionStringFieldDef(ConditionalStringFieldDef): - """ConditionalSelectionStringFieldDef schema wrapper - - Mapping(required=[selection]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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/ConditionalSelection'} - - def __init__(self, selection=Undefined, aggregate=Undefined, band=Undefined, bin=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, labelExpr=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(ConditionalSelectionStringFieldDef, self).__init__(selection=selection, - aggregate=aggregate, band=band, - bin=bin, field=field, format=format, - formatType=formatType, - labelExpr=labelExpr, timeUnit=timeUnit, - title=title, type=type, **kwds) - - -class ConditionalValueDefGradientstringnullExprRef(VegaLiteSchema): - """ConditionalValueDefGradientstringnullExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefGradientstringnullExprRef`, - :class:`ConditionalSelectionValueDefGradientstringnullExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(Gradient|string|null|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefGradientstringnullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefGradientstringnullExprRef(ConditionalValueDefGradientstringnullExprRef): - """ConditionalPredicateValueDefGradientstringnullExprRef schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefGradientstringnullExprRef(ConditionalValueDefGradientstringnullExprRef): - """ConditionalSelectionValueDefGradientstringnullExprRef schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefGradientstringnullExprRef, self).__init__(selection=selection, - value=value, **kwds) - - -class ConditionalValueDefTextExprRef(VegaLiteSchema): - """ConditionalValueDefTextExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefTextExprRef`, - :class:`ConditionalSelectionValueDefTextExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(Text|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefTextExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefTextExprRef(ConditionalValueDefTextExprRef): - """ConditionalPredicateValueDefTextExprRef schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefTextExprRef(ConditionalValueDefTextExprRef): - """ConditionalSelectionValueDefTextExprRef schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefTextExprRef, self).__init__(selection=selection, value=value, - **kwds) - - -class ConditionalValueDefnumber(VegaLiteSchema): - """ConditionalValueDefnumber schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefnumber`, - :class:`ConditionalSelectionValueDefnumber`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefnumber, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefnumber(ConditionalValueDefnumber): - """ConditionalPredicateValueDefnumber schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefnumber(ConditionalValueDefnumber): - """ConditionalSelectionValueDefnumber schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefnumber, self).__init__(selection=selection, value=value, - **kwds) - - -class ConditionalValueDefnumberArrayExprRef(VegaLiteSchema): - """ConditionalValueDefnumberArrayExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefnumberArrayExprRef`, - :class:`ConditionalSelectionValueDefnumberArrayExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(number[]|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefnumberArrayExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefnumberArrayExprRef(ConditionalValueDefnumberArrayExprRef): - """ConditionalPredicateValueDefnumberArrayExprRef schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefnumberArrayExprRef(ConditionalValueDefnumberArrayExprRef): - """ConditionalSelectionValueDefnumberArrayExprRef schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefnumberArrayExprRef, self).__init__(selection=selection, - value=value, **kwds) - - -class ConditionalValueDefnumberExprRef(VegaLiteSchema): - """ConditionalValueDefnumberExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefnumberExprRef`, - :class:`ConditionalSelectionValueDefnumberExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(number|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefnumberExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefnumberExprRef(ConditionalValueDefnumberExprRef): - """ConditionalPredicateValueDefnumberExprRef schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefnumberExprRef(ConditionalValueDefnumberExprRef): - """ConditionalSelectionValueDefnumberExprRef schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefnumberExprRef, self).__init__(selection=selection, - value=value, **kwds) - - -class ConditionalValueDefstringExprRef(VegaLiteSchema): - """ConditionalValueDefstringExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefstringExprRef`, - :class:`ConditionalSelectionValueDefstringExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(string|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefstringExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefstringExprRef(ConditionalValueDefstringExprRef): - """ConditionalPredicateValueDefstringExprRef schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefstringExprRef(ConditionalValueDefstringExprRef): - """ConditionalSelectionValueDefstringExprRef schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefstringExprRef, self).__init__(selection=selection, - value=value, **kwds) - - -class ConditionalValueDefstringnullExprRef(VegaLiteSchema): - """ConditionalValueDefstringnullExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefstringnullExprRef`, - :class:`ConditionalSelectionValueDefstringnullExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(string|null|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefstringnullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefstringnullExprRef(ConditionalValueDefstringnullExprRef): - """ConditionalPredicateValueDefstringnullExprRef schema wrapper - - Mapping(required=[test, value]) - - Attributes - ---------- - - 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 ConditionalSelectionValueDefstringnullExprRef(ConditionalValueDefstringnullExprRef): - """ConditionalSelectionValueDefstringnullExprRef schema wrapper - - Mapping(required=[selection, value]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - A `selection name `__, or a - series of `composed selections - `__. - 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/ConditionalSelection>'} - - def __init__(self, selection=Undefined, value=Undefined, **kwds): - super(ConditionalSelectionValueDefstringnullExprRef, self).__init__(selection=selection, - value=value, **kwds) - - -class Config(VegaLiteSchema): - """Config schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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. - mark : :class:`MarkConfig` - Mark Config - numberFormat : string - D3 Number format for guide labels and text marks. For example ``"s"`` for SI units. - Use `D3's number format pattern `__. - 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:`Parameter`) - Dynamic variables 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. - 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, mark=Undefined, numberFormat=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, 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, mark=mark, - numberFormat=numberFormat, 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, - 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=[]) - - Attributes - ---------- - - 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 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 Dictunknown(VegaLiteSchema): - """Dictunknown schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Dict'} - - def __init__(self, **kwds): - super(Dictunknown, 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]) - - Attributes - ---------- - - unionWith : anyOf(List(float), List(string), List(boolean), List(:class:`DateTime`)) - Customized domain values to be union with the field's values. - - 1) ``domain`` for *quantitative* fields can take one of the following forms: - - - * a two-element array with minimum and maximum values. - an array with more than two - entries, for `Piecewise quantitative scales - `__. (Alternatively, - the ``domainMid`` property can be set for a diverging scale.) - 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) ``domain`` for *temporal* fields can be a two-element array minimum and maximum - values, in the form of either timestamps or the `DateTime definition objects - `__. - - 3) ``domain`` for *ordinal* and *nominal* fields can be an array that lists valid - input 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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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"``. - 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"``. - """ - _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, y=Undefined, y2=Undefined, yError=Undefined, - yError2=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, y=y, y2=y2, yError=yError, - yError2=yError2, **kwds) - - -class EncodingSortFieldFieldName(VegaLiteSchema): - """EncodingSortFieldFieldName schema wrapper - - Mapping(required=[]) - A sort definition for sorting a discrete scale in an encoding field definition. - - Attributes - ---------- - - field : :class:`FieldName` - 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(EncodingSortFieldFieldName, self).__init__(field=field, op=op, order=order, **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=[]) - - Attributes - ---------- - - band : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - borders : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - 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]) - - Attributes - ---------- - - 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:`MarkConfigExprOrSignalRef`) - - borders : anyOf(boolean, :class:`MarkConfigExprOrSignalRef`) - - 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=[]) - - Attributes - ---------- - - 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:`MarkConfigExprOrSignalRef`) - - 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:`MarkConfigExprOrSignalRef`) - - """ - _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]) - - Attributes - ---------- - - 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:`MarkConfigExprOrSignalRef`) - - 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:`MarkConfigExprOrSignalRef`) - - """ - _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 ExprOrSignalRef(VegaLiteSchema): - """ExprOrSignalRef schema wrapper - - Mapping(required=[expr]) - - Attributes - ---------- - - expr : string - Vega expression (which can refer to Vega-Lite parameters). - """ - _schema = {'$ref': '#/definitions/ExprOrSignalRef'} - - def __init__(self, expr=Undefined, **kwds): - super(ExprOrSignalRef, self).__init__(expr=expr, **kwds) - - -class ExprRef(VegaLiteSchema): - """ExprRef schema wrapper - - Mapping(required=[expr]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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"``. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 : :class:`Header` - 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, band=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, band=band, - 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=[]) - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 : :class:`Header` - 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, band=Undefined, bin=Undefined, field=Undefined, - header=Undefined, sort=Undefined, timeUnit=Undefined, title=Undefined, type=Undefined, - **kwds): - super(FacetFieldDef, self).__init__(aggregate=aggregate, band=band, bin=bin, field=field, - header=header, sort=sort, timeUnit=timeUnit, title=title, - type=type, **kwds) - - -class FacetFieldDefFieldName(VegaLiteSchema): - """FacetFieldDefFieldName schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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:`FieldName` - **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 : :class:`Header` - An object defining properties of a facet's header. - sort : anyOf(:class:`SortArray`, :class:`SortOrder`, :class:`EncodingSortFieldFieldName`, - 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, band=Undefined, bin=Undefined, field=Undefined, - header=Undefined, sort=Undefined, timeUnit=Undefined, title=Undefined, type=Undefined, - **kwds): - super(FacetFieldDefFieldName, self).__init__(aggregate=aggregate, band=band, bin=bin, - field=field, header=header, sort=sort, - timeUnit=timeUnit, title=title, type=type, **kwds) - - -class FacetMapping(VegaLiteSchema): - """FacetMapping schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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 FacetMappingFieldName(VegaLiteSchema): - """FacetMappingFieldName schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - column : :class:`FacetFieldDefFieldName` - A field definition for the horizontal facet of trellis plots. - row : :class:`FacetFieldDefFieldName` - A field definition for the vertical facet of trellis plots. - """ - _schema = {'$ref': '#/definitions/FacetMapping'} - - def __init__(self, column=Undefined, row=Undefined, **kwds): - super(FacetMappingFieldName, self).__init__(column=column, row=row, **kwds) - - -class FacetedEncoding(VegaLiteSchema): - """FacetedEncoding schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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"``. - 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"``. - """ - _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, y=Undefined, - y2=Undefined, yError=Undefined, yError2=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, y=y, - y2=y2, yError=yError, yError2=yError2, **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. - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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, band=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(FieldDefWithoutScale, self).__init__(aggregate=aggregate, band=band, 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=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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, band=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, labelExpr=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionStringFieldDefstring, self).__init__(aggregate=aggregate, - band=band, bin=bin, - condition=condition, - field=field, - format=format, - formatType=formatType, - labelExpr=labelExpr, - timeUnit=timeUnit, - title=title, type=type, - **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 GeoJsonFeature(Fit): - """GeoJsonFeature schema wrapper - - Any - """ - _schema = {'$ref': '#/definitions/GeoJsonFeature'} - - def __init__(self, *args, **kwds): - super(GeoJsonFeature, self).__init__(*args, **kwds) - - -class GeoJsonFeatureCollection(Fit): - """GeoJsonFeatureCollection schema wrapper - - Any - """ - _schema = {'$ref': '#/definitions/GeoJsonFeatureCollection'} - - def __init__(self, *args, **kwds): - super(GeoJsonFeatureCollection, self).__init__(*args, **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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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. - - Attributes - ---------- - - format : anyOf(string, :class:`Dictunknown`) - 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=[]) - - Attributes - ---------- - - format : anyOf(string, :class:`Dictunknown`) - 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=[]) - - Attributes - ---------- - - frame : List([anyOf(None, float), 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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 InputBinding(Binding): - """InputBinding schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - autocomplete : string - - debounce : float - - element : :class:`Element` - - input : string - - name : string - - placeholder : string - - type : string - - """ - _schema = {'$ref': '#/definitions/InputBinding'} - - def __init__(self, autocomplete=Undefined, debounce=Undefined, element=Undefined, input=Undefined, - name=Undefined, placeholder=Undefined, type=Undefined, **kwds): - super(InputBinding, self).__init__(autocomplete=autocomplete, debounce=debounce, - element=element, input=input, name=name, - placeholder=placeholder, type=type, **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=[]) - - Attributes - ---------- - - bind : string - Establishes a two-way binding between the interval selection and the scales used - within the same view. This allows a user to interactively pan and zoom the view. - - **See also:** `bind `__ - documentation. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. Can be a `Event Stream - `__ or ``false`` to disable. - - **Default value:** ``dblclick``. - - **See also:** `clear `__ - documentation. - empty : enum('all', 'none') - By default, ``all`` data values are considered to lie within an empty selection. - When set to ``none``, empty selections contain no data values. - 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:** `encodings `__ - 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:** `fields `__ - documentation. - init : :class:`SelectionInitIntervalMapping` - Initialize the selection with a mapping between `projected channels or field names - `__ and arrays of initial - values. - - **See also:** `init `__ - 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 `__ - 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 - `__. - 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. - - **See also:** `resolve - `__ 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. - - **Default value:** ``true``, which corresponds to ``[mousedown, window:mouseup] > - window:mousemove!`` which corresponds to clicks and dragging within an interval - selection to reposition it. - - **See also:** `translate `__ - 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. - - **Default value:** ``true``, which corresponds to ``wheel!``. - - **See also:** `zoom `__ - documentation. - """ - _schema = {'$ref': '#/definitions/IntervalSelectionConfig'} - - def __init__(self, bind=Undefined, clear=Undefined, empty=Undefined, encodings=Undefined, - fields=Undefined, init=Undefined, mark=Undefined, on=Undefined, resolve=Undefined, - translate=Undefined, zoom=Undefined, **kwds): - super(IntervalSelectionConfig, self).__init__(bind=bind, clear=clear, empty=empty, - encodings=encodings, fields=fields, init=init, - mark=mark, on=on, resolve=resolve, - translate=translate, zoom=zoom, **kwds) - - -class JoinAggregateFieldDef(VegaLiteSchema): - """JoinAggregateFieldDef schema wrapper - - Mapping(required=[op, as]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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`, :class:`NumericValueDef`) - """ - _schema = {'$ref': '#/definitions/LatLongDef'} - - def __init__(self, *args, **kwds): - super(LatLongDef, self).__init__(*args, **kwds) - - -class LatLongFieldDef(LatLongDef): - """LatLongFieldDef schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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, band=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(LatLongFieldDef, self).__init__(aggregate=aggregate, band=band, bin=bin, field=field, - timeUnit=timeUnit, title=title, type=type, **kwds) - - -class LayerRepeatMapping(VegaLiteSchema): - """LayerRepeatMapping schema wrapper - - Mapping(required=[layer]) - - Attributes - ---------- - - 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. - - Attributes - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - - clipHeight : anyOf(float, :class:`ExprRef`) - - columnPadding : anyOf(float, :class:`ExprRef`) - - columns : anyOf(float, :class:`ExprRef`) - - cornerRadius : anyOf(float, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - 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`) - - format : anyOf(string, :class:`Dictunknown`) - 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`) - - gradientOpacity : anyOf(float, :class:`ExprRef`) - - gradientStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - gradientStrokeWidth : anyOf(float, :class:`ExprRef`) - - gradientThickness : anyOf(float, :class:`ExprRef`) - - gridAlign : anyOf(:class:`LayoutAlign`, :class:`ExprRef`) - - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`) - - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - 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`) - - labelFontSize : anyOf(float, :class:`ExprRef`) - - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - labelLimit : anyOf(float, :class:`ExprRef`) - - labelOffset : anyOf(float, :class:`ExprRef`) - - labelOpacity : anyOf(float, :class:`ExprRef`) - - labelOverlap : anyOf(:class:`LabelOverlap`, :class:`ExprRef`) - - labelPadding : anyOf(float, :class:`ExprRef`) - - labelSeparation : anyOf(float, :class:`ExprRef`) - - legendX : anyOf(float, :class:`ExprRef`) - - legendY : anyOf(float, :class:`ExprRef`) - - offset : anyOf(float, :class:`ExprRef`) - - 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`) - - rowPadding : anyOf(float, :class:`ExprRef`) - - strokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolDash : anyOf(List(float), :class:`ExprRef`) - - symbolDashOffset : anyOf(float, :class:`ExprRef`) - - symbolFillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolLimit : anyOf(float, :class:`ExprRef`) - - symbolOffset : anyOf(float, :class:`ExprRef`) - - symbolOpacity : anyOf(float, :class:`ExprRef`) - - symbolSize : anyOf(float, :class:`ExprRef`) - - symbolStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolStrokeWidth : anyOf(float, :class:`ExprRef`) - - symbolType : anyOf(:class:`SymbolShape`, :class:`ExprRef`) - - tickCount : anyOf(:class:`TickCount`, :class:`ExprRef`) - - 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`) - - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - titleFont : anyOf(string, :class:`ExprRef`) - - titleFontSize : anyOf(float, :class:`ExprRef`) - - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - titleLimit : anyOf(float, :class:`ExprRef`) - - titleLineHeight : anyOf(float, :class:`ExprRef`) - - titleOpacity : anyOf(float, :class:`ExprRef`) - - titleOrient : anyOf(:class:`Orient`, :class:`ExprRef`) - - titlePadding : anyOf(float, :class:`ExprRef`) - - 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=[]) - - Attributes - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - - clipHeight : anyOf(float, :class:`ExprRef`) - - columnPadding : anyOf(float, :class:`ExprRef`) - - columns : anyOf(float, :class:`ExprRef`) - - cornerRadius : anyOf(float, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - 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`) - - gradientDirection : anyOf(:class:`Orientation`, :class:`ExprRef`) - - 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`) - - gradientLabelOffset : anyOf(float, :class:`ExprRef`) - - gradientLength : anyOf(float, :class:`ExprRef`) - - gradientOpacity : anyOf(float, :class:`ExprRef`) - - gradientStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - gradientStrokeWidth : anyOf(float, :class:`ExprRef`) - - gradientThickness : anyOf(float, :class:`ExprRef`) - - 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`) - - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`) - - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - labelFont : anyOf(string, :class:`ExprRef`) - - labelFontSize : anyOf(float, :class:`ExprRef`) - - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - labelLimit : anyOf(float, :class:`ExprRef`) - - labelOffset : anyOf(float, :class:`ExprRef`) - - labelOpacity : anyOf(float, :class:`ExprRef`) - - 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`) - - labelSeparation : anyOf(float, :class:`ExprRef`) - - layout : :class:`ExprRef` - - legendX : anyOf(float, :class:`ExprRef`) - - legendY : anyOf(float, :class:`ExprRef`) - - offset : anyOf(float, :class:`ExprRef`) - - 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`) - - rowPadding : anyOf(float, :class:`ExprRef`) - - strokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - symbolBaseFillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolBaseStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolDash : anyOf(List(float), :class:`ExprRef`) - - symbolDashOffset : anyOf(float, :class:`ExprRef`) - - symbolDirection : anyOf(:class:`Orientation`, :class:`ExprRef`) - - symbolFillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolLimit : anyOf(float, :class:`ExprRef`) - - symbolOffset : anyOf(float, :class:`ExprRef`) - - symbolOpacity : anyOf(float, :class:`ExprRef`) - - symbolSize : anyOf(float, :class:`ExprRef`) - - symbolStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - symbolStrokeWidth : anyOf(float, :class:`ExprRef`) - - symbolType : anyOf(:class:`SymbolShape`, :class:`ExprRef`) - - tickCount : anyOf(:class:`TickCount`, :class:`ExprRef`) - - title : None - Set to null to disable title for the axis, legend, or header. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - titleFont : anyOf(string, :class:`ExprRef`) - - titleFontSize : anyOf(float, :class:`ExprRef`) - - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - titleLimit : anyOf(float, :class:`ExprRef`) - - titleLineHeight : anyOf(float, :class:`ExprRef`) - - titleOpacity : anyOf(float, :class:`ExprRef`) - - titleOrient : anyOf(:class:`Orient`, :class:`ExprRef`) - - titlePadding : anyOf(float, :class:`ExprRef`) - - unselectedOpacity : float - The opacity of unselected legend entries. - - **Default value:** 0.35. - zindex : anyOf(float, :class:`ExprRef`) - - """ - _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=[]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - lineBreak : anyOf(string, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - tension : anyOf(float, :class:`ExprRef`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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. - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, - timeUnitBand=Undefined, timeUnitBandPosition=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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, tooltip=tooltip, - url=url, width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class LinearGradient(Gradient): - """LinearGradient schema wrapper - - Mapping(required=[gradient, stops]) - - Attributes - ---------- - - 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 LookupData(VegaLiteSchema): - """LookupData schema wrapper - - Mapping(required=[data, key]) - - Attributes - ---------- - - 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, selection]) - - Attributes - ---------- - - key : :class:`FieldName` - Key in data to lookup. - selection : string - Selection 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, selection=Undefined, fields=Undefined, **kwds): - super(LookupSelection, self).__init__(key=key, selection=selection, 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=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - lineBreak : anyOf(string, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - tension : anyOf(float, :class:`ExprRef`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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. - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, - timeUnitBand=Undefined, timeUnitBandPosition=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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, tooltip=tooltip, - url=url, width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class MarkConfigExprOrSignalRef(VegaLiteSchema): - """MarkConfigExprOrSignalRef schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - align : anyOf(:class:`Align`, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - - aria : anyOf(boolean, :class:`ExprOrSignalRef`) - - ariaRole : anyOf(string, :class:`ExprOrSignalRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprOrSignalRef`) - - aspect : anyOf(boolean, :class:`ExprOrSignalRef`) - - baseline : anyOf(:class:`TextBaseline`, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprOrSignalRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprOrSignalRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprOrSignalRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprOrSignalRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprOrSignalRef`) - - description : anyOf(string, :class:`ExprOrSignalRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprOrSignalRef`) - - dx : anyOf(float, :class:`ExprOrSignalRef`) - - dy : anyOf(float, :class:`ExprOrSignalRef`) - - ellipsis : anyOf(string, :class:`ExprOrSignalRef`) - - endAngle : anyOf(float, :class:`ExprOrSignalRef`) - - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprOrSignalRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprOrSignalRef`) - - 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:`ExprOrSignalRef`) - - fontSize : anyOf(float, :class:`ExprOrSignalRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprOrSignalRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprOrSignalRef`) - - height : anyOf(float, :class:`ExprOrSignalRef`) - - href : anyOf(:class:`URI`, :class:`ExprOrSignalRef`) - - innerRadius : anyOf(float, :class:`ExprOrSignalRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprOrSignalRef`) - - 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:`ExprOrSignalRef`) - - lineBreak : anyOf(string, :class:`ExprOrSignalRef`) - - lineHeight : anyOf(float, :class:`ExprOrSignalRef`) - - opacity : anyOf(float, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - padAngle : anyOf(float, :class:`ExprOrSignalRef`) - - radius : anyOf(float, :class:`ExprOrSignalRef`) - 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. - radius2 : anyOf(float, :class:`ExprOrSignalRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprOrSignalRef`) - - size : anyOf(float, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - - startAngle : anyOf(float, :class:`ExprOrSignalRef`) - - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - - strokeDash : anyOf(List(float), :class:`ExprOrSignalRef`) - - strokeDashOffset : anyOf(float, :class:`ExprOrSignalRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprOrSignalRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprOrSignalRef`) - - strokeOffset : anyOf(float, :class:`ExprOrSignalRef`) - - strokeOpacity : anyOf(float, :class:`ExprOrSignalRef`) - - strokeWidth : anyOf(float, :class:`ExprOrSignalRef`) - - tension : anyOf(float, :class:`ExprOrSignalRef`) - - text : anyOf(:class:`Text`, :class:`ExprOrSignalRef`) - - theta : anyOf(float, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - timeUnitBand : 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. - 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. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprOrSignalRef`, - 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:`ExprOrSignalRef`) - - width : anyOf(float, :class:`ExprOrSignalRef`) - - x : anyOf(float, string, :class:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - 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:`ExprOrSignalRef`) - 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, - timeUnitBand=Undefined, timeUnitBandPosition=Undefined, tooltip=Undefined, - url=Undefined, width=Undefined, x=Undefined, x2=Undefined, y=Undefined, y2=Undefined, - **kwds): - super(MarkConfigExprOrSignalRef, 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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, - tooltip=tooltip, url=url, width=width, x=x, - x2=x2, y=y, y2=y2, **kwds) - - -class MarkDef(AnyMark): - """MarkDef schema wrapper - - Mapping(required=[type]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - 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`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - discreteBandSize : float - 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`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - 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`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - radius2Offset : anyOf(float, :class:`ExprRef`) - Offset for radius2. - radiusOffset : anyOf(float, :class:`ExprRef`) - Offset for radius. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - 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`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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`` - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, - timeUnitBand=Undefined, timeUnitBandPosition=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, timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, 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=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - condition : anyOf(:class:`ConditionalValueDefGradientstringnullExprRef`, - List(:class:`ConditionalValueDefGradientstringnullExprRef`)) - One or more value definition(s) with `a selection 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. - 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, band=Undefined, condition=Undefined, datum=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefGradientstringnull, self).__init__(band=band, - condition=condition, - datum=datum, - type=type, **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull(ColorDef, MarkPropDefGradientstringnull): - """FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull schema wrapper - - Mapping(required=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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, band=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, - band=band, - 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 MultiSelectionConfig(VegaLiteSchema): - """MultiSelectionConfig schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - bind : :class:`LegendBinding` - When set, a selection is populated 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. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. Can be a `Event Stream - `__ or ``false`` to disable. - - **Default value:** ``dblclick``. - - **See also:** `clear `__ - documentation. - empty : enum('all', 'none') - By default, ``all`` data values are considered to lie within an empty selection. - When set to ``none``, empty selections contain no data values. - 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:** `encodings `__ - 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:** `fields `__ - documentation. - init : List(:class:`SelectionInitMapping`) - Initialize the selection with a mapping between `projected channels or field names - `__ and an initial value (or - array of values). - - **See also:** `init `__ - 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. - - **See also:** `nearest `__ - 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 - `__. - 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. - - **See also:** `resolve - `__ documentation. - toggle : anyOf(string, boolean) - Controls whether data values should be toggled or only ever inserted into multi - selections. Can be ``true``, ``false`` (for insertion only), or a `Vega expression - `__. - - **Default value:** ``true``, which corresponds to ``event.shiftKey`` (i.e., data - values are toggled when a user interacts with the shift-key pressed). - - Setting the value to the Vega expression ``"true"`` will toggle data values without - the user pressing the shift-key. - - **See also:** `toggle `__ - documentation. - """ - _schema = {'$ref': '#/definitions/MultiSelectionConfig'} - - def __init__(self, bind=Undefined, clear=Undefined, empty=Undefined, encodings=Undefined, - fields=Undefined, init=Undefined, nearest=Undefined, on=Undefined, resolve=Undefined, - toggle=Undefined, **kwds): - super(MultiSelectionConfig, self).__init__(bind=bind, clear=clear, empty=empty, - encodings=encodings, fields=fields, init=init, - nearest=nearest, on=on, resolve=resolve, - toggle=toggle, **kwds) - - -class NamedData(DataSource): - """NamedData schema wrapper - - Mapping(required=[name]) - - Attributes - ---------- - - name : string - Provide a placeholder name and bind data at runtime. - 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 NormalizedSpec(VegaLiteSchema): - """NormalizedSpec schema wrapper - - anyOf(:class:`FacetedUnitSpec`, :class:`LayerSpec`, :class:`RepeatSpec`, - :class:`NormalizedFacetSpec`, :class:`NormalizedConcatSpecGenericSpec`, - :class:`NormalizedVConcatSpecGenericSpec`, :class:`NormalizedHConcatSpecGenericSpec`) - Any specification in Vega-Lite. - """ - _schema = {'$ref': '#/definitions/NormalizedSpec'} - - def __init__(self, *args, **kwds): - super(NormalizedSpec, self).__init__(*args, **kwds) - - -class NormalizedConcatSpecGenericSpec(NormalizedSpec): - """NormalizedConcatSpecGenericSpec schema wrapper - - Mapping(required=[concat]) - Base interface for a generalized concatenation specification. - - Attributes - ---------- - - concat : List(:class:`NormalizedSpec`) - 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/NormalizedConcatSpec'} - - 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(NormalizedConcatSpecGenericSpec, 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 NormalizedFacetSpec(NormalizedSpec): - """NormalizedFacetSpec schema wrapper - - Mapping(required=[facet, spec]) - Base interface for a facet specification. - - Attributes - ---------- - - 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/NormalizedFacetSpec'} - - 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(NormalizedFacetSpec, 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 NormalizedHConcatSpecGenericSpec(NormalizedSpec): - """NormalizedHConcatSpecGenericSpec schema wrapper - - Mapping(required=[hconcat]) - Base interface for a horizontal concatenation specification. - - Attributes - ---------- - - hconcat : List(:class:`NormalizedSpec`) - 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/NormalizedHConcatSpec'} - - 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(NormalizedHConcatSpecGenericSpec, self).__init__(hconcat=hconcat, bounds=bounds, - center=center, data=data, - description=description, name=name, - resolve=resolve, spacing=spacing, - title=title, transform=transform, **kwds) - - -class NormalizedVConcatSpecGenericSpec(NormalizedSpec): - """NormalizedVConcatSpecGenericSpec schema wrapper - - Mapping(required=[vconcat]) - Base interface for a vertical concatenation specification. - - Attributes - ---------- - - vconcat : List(:class:`NormalizedSpec`) - 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/NormalizedVConcatSpec'} - - 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(NormalizedVConcatSpecGenericSpec, self).__init__(vconcat=vconcat, bounds=bounds, - center=center, data=data, - description=description, name=name, - resolve=resolve, spacing=spacing, - title=title, transform=transform, **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=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - condition : anyOf(:class:`ConditionalValueDefnumberArrayExprRef`, - List(:class:`ConditionalValueDefnumberArrayExprRef`)) - One or more value definition(s) with `a selection 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. - 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, band=Undefined, condition=Undefined, datum=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefnumberArray, self).__init__(band=band, - condition=condition, - datum=datum, type=type, - **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray(MarkPropDefnumberArray, NumericArrayMarkPropDef): - """FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray schema wrapper - - Mapping(required=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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, band=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, - band=band, - 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=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - condition : anyOf(:class:`ConditionalValueDefnumberExprRef`, - List(:class:`ConditionalValueDefnumberExprRef`)) - One or more value definition(s) with `a selection 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. - 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, band=Undefined, condition=Undefined, datum=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefnumber, self).__init__(band=band, condition=condition, - datum=datum, type=type, **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefnumber(MarkPropDefnumber, NumericMarkPropDef): - """FieldOrDatumDefWithConditionMarkPropFieldDefnumber schema wrapper - - Mapping(required=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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, band=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, - band=band, bin=bin, - condition=condition, - field=field, - legend=legend, - scale=scale, sort=sort, - timeUnit=timeUnit, - title=title, type=type, - **kwds) - - -class NumericValueDef(LatLongDef): - """NumericValueDef schema wrapper - - Mapping(required=[value]) - Definition object for a constant value (primitive value or gradient definition) of an - encoding channel. - - Attributes - ---------- - - 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/NumericValueDef'} - - def __init__(self, value=Undefined, **kwds): - super(NumericValueDef, self).__init__(value=value, **kwds) - - -class OrderFieldDef(VegaLiteSchema): - """OrderFieldDef schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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, band=Undefined, bin=Undefined, field=Undefined, - sort=Undefined, timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(OrderFieldDef, self).__init__(aggregate=aggregate, band=band, bin=bin, field=field, - sort=sort, timeUnit=timeUnit, title=title, type=type, **kwds) - - -class OrderValueDef(VegaLiteSchema): - """OrderValueDef schema wrapper - - Mapping(required=[value]) - - Attributes - ---------- - - 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 selection 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=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - lineBreak : anyOf(string, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - radius2Offset : anyOf(float, :class:`ExprRef`) - Offset for radius2. - radiusOffset : anyOf(float, :class:`ExprRef`) - Offset for radius. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - 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`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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. - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, timeUnitBand=Undefined, - timeUnitBandPosition=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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, 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 Parameter(VegaLiteSchema): - """Parameter schema wrapper - - Mapping(required=[name]) - - Attributes - ---------- - - name : string - Required. A unique name for the 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. - description : string - A text description of the parameter, useful for inline documentation. - 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/Parameter'} - - def __init__(self, name=Undefined, bind=Undefined, description=Undefined, expr=Undefined, - value=Undefined, **kwds): - super(Parameter, self).__init__(name=name, bind=bind, description=description, expr=expr, - value=value, **kwds) - - -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 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 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=[]) - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, - :class:`RepeatRef`) - A constant value in data domain. - 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, band=Undefined, datum=Undefined, type=Undefined, **kwds): - super(DatumDef, self).__init__(band=band, datum=datum, type=type, **kwds) - - -class PositionDatumDefBase(PolarDef): - """PositionDatumDefBase schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 `__. - :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. - 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, band=Undefined, datum=Undefined, scale=Undefined, stack=Undefined, - type=Undefined, **kwds): - super(PositionDatumDefBase, self).__init__(band=band, datum=datum, scale=scale, stack=stack, - 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=[]) - - Attributes - ---------- - - 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. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 `__. - :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. - 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, band=Undefined, datum=Undefined, impute=Undefined, - scale=Undefined, stack=Undefined, type=Undefined, **kwds): - super(PositionDatumDef, self).__init__(axis=axis, band=band, datum=datum, impute=impute, - scale=scale, stack=stack, type=type, **kwds) - - -class PositionFieldDef(PositionDef): - """PositionFieldDef schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 `__. - :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, band=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, band=band, 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=[]) - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 `__. - :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, band=Undefined, bin=Undefined, field=Undefined, - scale=Undefined, sort=Undefined, stack=Undefined, timeUnit=Undefined, title=Undefined, - type=Undefined, **kwds): - super(PositionFieldDefBase, self).__init__(aggregate=aggregate, band=band, 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. - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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:`SelectionPredicate`, 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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 Projection(VegaLiteSchema): - """Projection schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - center : :class:`Vector2number` - The projection's center, a two-element array of longitude and latitude in degrees. - - **Default value:** ``[0, 0]`` - clipAngle : float - The projection's clipping circle radius to the specified angle in degrees. If - ``null``, switches to `antimeridian `__ cutting - rather than small-circle clipping. - clipExtent : :class:`Vector2Vector2number` - 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 : float - - distance : float - - extent : :class:`Vector2Vector2number` - - fit : anyOf(:class:`Fit`, List(:class:`Fit`)) - - fraction : float - - lobes : float - - parallel : float - - parallels : List(float) - For conic projections, the `two standard parallels - `__ that define the map layout. - The default depends on the specific conic projection used. - pointRadius : float - 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 : float - 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 : float - - ratio : float - - reflectX : boolean - - reflectY : boolean - - rotate : anyOf(:class:`Vector2number`, :class:`Vector3number`) - 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 : float - 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 : :class:`Vector2number` - - spacing : float - - tilt : float - - translate : :class:`Vector2number` - The projection’s translation offset as a two-element array ``[tx, ty]``. - type : :class:`ProjectionType` - 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:** ``mercator`` - """ - _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=[]) - - Attributes - ---------- - - center : :class:`Vector2number` - The projection's center, a two-element array of longitude and latitude in degrees. - - **Default value:** ``[0, 0]`` - clipAngle : float - The projection's clipping circle radius to the specified angle in degrees. If - ``null``, switches to `antimeridian `__ cutting - rather than small-circle clipping. - clipExtent : :class:`Vector2Vector2number` - 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 : float - - distance : float - - extent : :class:`Vector2Vector2number` - - fit : anyOf(:class:`Fit`, List(:class:`Fit`)) - - fraction : float - - lobes : float - - parallel : float - - parallels : List(float) - For conic projections, the `two standard parallels - `__ that define the map layout. - The default depends on the specific conic projection used. - pointRadius : float - 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 : float - 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 : float - - ratio : float - - reflectX : boolean - - reflectY : boolean - - rotate : anyOf(:class:`Vector2number`, :class:`Vector3number`) - 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 : float - 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 : :class:`Vector2number` - - spacing : float - - tilt : float - - translate : :class:`Vector2number` - The projection’s translation offset as a two-element array ``[tx, ty]``. - type : :class:`ProjectionType` - 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:** ``mercator`` - """ - _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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - discreteBandSize : float - 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`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - lineBreak : anyOf(string, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - tension : anyOf(float, :class:`ExprRef`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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. - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, timeUnitBand=Undefined, - timeUnitBandPosition=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, - timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, tooltip=tooltip, - url=url, width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class RepeatMapping(VegaLiteSchema): - """RepeatMapping schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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. - - Attributes - ---------- - - 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"``. - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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"``. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 : :class:`Header` - 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, band=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, band=band, - 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=[]) - - Attributes - ---------- - - 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:`SelectionExtent`, :class:`DomainUnionWith`, - :class:`ExprRef`) - Customized domain values in the form of constant values or dynamic values driven by - a selection. - - 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 selection 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; ``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`)), - Mapping(required=[field])) - 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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - bandPaddingInner : anyOf(float, :class:`ExprRef`) - Default inner padding for ``x`` and ``y`` band-ordinal scales. - - **Default value:** - ``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-ordinal scales. - - **Default value:** ``paddingInner/2`` (which makes *width/height = number of unique - values * step* ) - 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 scales. - - **Default:** ``5`` 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`` - 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). - """ - _schema = {'$ref': '#/definitions/ScaleConfig'} - - def __init__(self, bandPaddingInner=Undefined, bandPaddingOuter=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, - pointPadding=Undefined, quantileCount=Undefined, quantizeCount=Undefined, - rectBandPaddingInner=Undefined, round=Undefined, useUnaggregatedDomain=Undefined, - xReverse=Undefined, **kwds): - super(ScaleConfig, self).__init__(bandPaddingInner=bandPaddingInner, - bandPaddingOuter=bandPaddingOuter, - 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, pointPadding=pointPadding, - quantileCount=quantileCount, quantizeCount=quantizeCount, - rectBandPaddingInner=rectBandPaddingInner, round=round, - useUnaggregatedDomain=useUnaggregatedDomain, - xReverse=xReverse, **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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - 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` - - y : :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, y=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, y=y, **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]) - - Attributes - ---------- - - 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``. - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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, band=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, **kwds): - super(SecondaryFieldDef, self).__init__(aggregate=aggregate, band=band, bin=bin, field=field, - timeUnit=timeUnit, title=title, **kwds) - - -class SelectionComposition(VegaLiteSchema): - """SelectionComposition schema wrapper - - anyOf(:class:`SelectionNot`, :class:`SelectionAnd`, :class:`SelectionOr`, string) - """ - _schema = {'$ref': '#/definitions/SelectionComposition'} - - def __init__(self, *args, **kwds): - super(SelectionComposition, self).__init__(*args, **kwds) - - -class SelectionAnd(SelectionComposition): - """SelectionAnd schema wrapper - - Mapping(required=[and]) - - Attributes - ---------- - - and : List(:class:`SelectionComposition`) - - """ - _schema = {'$ref': '#/definitions/SelectionAnd'} - - def __init__(self, **kwds): - super(SelectionAnd, self).__init__(**kwds) - - -class SelectionConfig(VegaLiteSchema): - """SelectionConfig schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - interval : :class:`IntervalSelectionConfig` - 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. - multi : :class:`MultiSelectionConfig` - The default definition for a `multi - `__ selection. All - properties and transformations for a multi selection definition (except ``type`` ) - may be specified here. - - For instance, setting ``multi`` to ``{"toggle": "event.altKey"}`` adds additional - values to multi selections when clicking with the alt-key pressed by default. - single : :class:`SingleSelectionConfig` - The default definition for a `single - `__ selection. All - properties and transformations for a single selection definition (except ``type`` - ) may be specified here. - - For instance, setting ``single`` to ``{"on": "dblclick"}`` populates single - selections on double-click by default. - """ - _schema = {'$ref': '#/definitions/SelectionConfig'} - - def __init__(self, interval=Undefined, multi=Undefined, single=Undefined, **kwds): - super(SelectionConfig, self).__init__(interval=interval, multi=multi, single=single, **kwds) - - -class SelectionDef(VegaLiteSchema): - """SelectionDef schema wrapper - - anyOf(:class:`SingleSelection`, :class:`MultiSelection`, :class:`IntervalSelection`) - """ - _schema = {'$ref': '#/definitions/SelectionDef'} - - def __init__(self, *args, **kwds): - super(SelectionDef, self).__init__(*args, **kwds) - - -class IntervalSelection(SelectionDef): - """IntervalSelection schema wrapper - - Mapping(required=[type]) - - Attributes - ---------- - - type : string - Determines the default event processing and data query for the selection. Vega-Lite - currently supports three selection types: - - - * ``"single"`` -- to select a single discrete data value on ``click``. - ``"multi"`` - -- to select multiple discrete data value; 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 : string - Establishes a two-way binding between the interval selection and the scales used - within the same view. This allows a user to interactively pan and zoom the view. - - **See also:** `bind `__ - documentation. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. Can be a `Event Stream - `__ or ``false`` to disable. - - **Default value:** ``dblclick``. - - **See also:** `clear `__ - documentation. - empty : enum('all', 'none') - By default, ``all`` data values are considered to lie within an empty selection. - When set to ``none``, empty selections contain no data values. - 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:** `encodings `__ - 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:** `fields `__ - documentation. - init : :class:`SelectionInitIntervalMapping` - Initialize the selection with a mapping between `projected channels or field names - `__ and arrays of initial - values. - - **See also:** `init `__ - 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 `__ - 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 - `__. - 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. - - **See also:** `resolve - `__ 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. - - **Default value:** ``true``, which corresponds to ``[mousedown, window:mouseup] > - window:mousemove!`` which corresponds to clicks and dragging within an interval - selection to reposition it. - - **See also:** `translate `__ - 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. - - **Default value:** ``true``, which corresponds to ``wheel!``. - - **See also:** `zoom `__ - documentation. - """ - _schema = {'$ref': '#/definitions/IntervalSelection'} - - def __init__(self, type=Undefined, bind=Undefined, clear=Undefined, empty=Undefined, - encodings=Undefined, fields=Undefined, init=Undefined, mark=Undefined, on=Undefined, - resolve=Undefined, translate=Undefined, zoom=Undefined, **kwds): - super(IntervalSelection, self).__init__(type=type, bind=bind, clear=clear, empty=empty, - encodings=encodings, fields=fields, init=init, - mark=mark, on=on, resolve=resolve, translate=translate, - zoom=zoom, **kwds) - - -class MultiSelection(SelectionDef): - """MultiSelection schema wrapper - - Mapping(required=[type]) - - Attributes - ---------- - - type : string - Determines the default event processing and data query for the selection. Vega-Lite - currently supports three selection types: - - - * ``"single"`` -- to select a single discrete data value on ``click``. - ``"multi"`` - -- to select multiple discrete data value; 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 : :class:`LegendBinding` - When set, a selection is populated 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. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. Can be a `Event Stream - `__ or ``false`` to disable. - - **Default value:** ``dblclick``. - - **See also:** `clear `__ - documentation. - empty : enum('all', 'none') - By default, ``all`` data values are considered to lie within an empty selection. - When set to ``none``, empty selections contain no data values. - 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:** `encodings `__ - 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:** `fields `__ - documentation. - init : List(:class:`SelectionInitMapping`) - Initialize the selection with a mapping between `projected channels or field names - `__ and an initial value (or - array of values). - - **See also:** `init `__ - 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. - - **See also:** `nearest `__ - 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 - `__. - 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. - - **See also:** `resolve - `__ documentation. - toggle : anyOf(string, boolean) - Controls whether data values should be toggled or only ever inserted into multi - selections. Can be ``true``, ``false`` (for insertion only), or a `Vega expression - `__. - - **Default value:** ``true``, which corresponds to ``event.shiftKey`` (i.e., data - values are toggled when a user interacts with the shift-key pressed). - - Setting the value to the Vega expression ``"true"`` will toggle data values without - the user pressing the shift-key. - - **See also:** `toggle `__ - documentation. - """ - _schema = {'$ref': '#/definitions/MultiSelection'} - - def __init__(self, type=Undefined, bind=Undefined, clear=Undefined, empty=Undefined, - encodings=Undefined, fields=Undefined, init=Undefined, nearest=Undefined, on=Undefined, - resolve=Undefined, toggle=Undefined, **kwds): - super(MultiSelection, self).__init__(type=type, bind=bind, clear=clear, empty=empty, - encodings=encodings, fields=fields, init=init, - nearest=nearest, on=on, resolve=resolve, toggle=toggle, - **kwds) - - -class SelectionExtent(BinExtent): - """SelectionExtent schema wrapper - - anyOf(Mapping(required=[selection]), Mapping(required=[selection])) - """ - _schema = {'$ref': '#/definitions/SelectionExtent'} - - def __init__(self, *args, **kwds): - super(SelectionExtent, self).__init__(*args, **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. - - Attributes - ---------- - - 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 SelectionNot(SelectionComposition): - """SelectionNot schema wrapper - - Mapping(required=[not]) - - Attributes - ---------- - - not : :class:`SelectionComposition` - - """ - _schema = {'$ref': '#/definitions/SelectionNot'} - - def __init__(self, **kwds): - super(SelectionNot, self).__init__(**kwds) - - -class SelectionOr(SelectionComposition): - """SelectionOr schema wrapper - - Mapping(required=[or]) - - Attributes - ---------- - - or : List(:class:`SelectionComposition`) - - """ - _schema = {'$ref': '#/definitions/SelectionOr'} - - def __init__(self, **kwds): - super(SelectionOr, self).__init__(**kwds) - - -class SelectionPredicate(Predicate): - """SelectionPredicate schema wrapper - - Mapping(required=[selection]) - - Attributes - ---------- - - selection : :class:`SelectionComposition` - Filter using a selection name or a logical composition of selection names. - """ - _schema = {'$ref': '#/definitions/SelectionPredicate'} - - def __init__(self, selection=Undefined, **kwds): - super(SelectionPredicate, self).__init__(selection=selection, **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 SequenceGenerator(Generator): - """SequenceGenerator schema wrapper - - Mapping(required=[sequence]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - condition : anyOf(:class:`ConditionalValueDefstringnullExprRef`, - List(:class:`ConditionalValueDefstringnullExprRef`)) - One or more value definition(s) with `a selection 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. - 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, band=Undefined, condition=Undefined, datum=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefstringnull, self).__init__(band=band, - condition=condition, - datum=datum, type=type, - **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull(MarkPropDefstringnullTypeForShape, ShapeDef): - """FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull schema wrapper - - Mapping(required=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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, band=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, - band=band, - 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=[]) - - Attributes - ---------- - - 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=[]) - - y : Mapping(required=[]) - - y2 : Mapping(required=[]) - - yError : Mapping(required=[]) - - yError2 : 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, y=Undefined, y2=Undefined, yError=Undefined, - yError2=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, y=y, y2=y2, yError=yError, - yError2=yError2, **kwds) - - -class SingleDefUnitChannel(VegaLiteSchema): - """SingleDefUnitChannel schema wrapper - - enum('x', 'y', '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 SingleSelection(SelectionDef): - """SingleSelection schema wrapper - - Mapping(required=[type]) - - Attributes - ---------- - - type : string - Determines the default event processing and data query for the selection. Vega-Lite - currently supports three selection types: - - - * ``"single"`` -- to select a single discrete data value on ``click``. - ``"multi"`` - -- to select multiple discrete data value; 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`) - 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. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. Can be a `Event Stream - `__ or ``false`` to disable. - - **Default value:** ``dblclick``. - - **See also:** `clear `__ - documentation. - empty : enum('all', 'none') - By default, ``all`` data values are considered to lie within an empty selection. - When set to ``none``, empty selections contain no data values. - 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:** `encodings `__ - 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:** `fields `__ - documentation. - init : :class:`SelectionInitMapping` - Initialize the selection with a mapping between `projected channels or field names - `__ and initial values. - - **See also:** `init `__ - 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. - - **See also:** `nearest `__ - 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 - `__. - 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. - - **See also:** `resolve - `__ documentation. - """ - _schema = {'$ref': '#/definitions/SingleSelection'} - - def __init__(self, type=Undefined, bind=Undefined, clear=Undefined, empty=Undefined, - encodings=Undefined, fields=Undefined, init=Undefined, nearest=Undefined, on=Undefined, - resolve=Undefined, **kwds): - super(SingleSelection, self).__init__(type=type, bind=bind, clear=clear, empty=empty, - encodings=encodings, fields=fields, init=init, - nearest=nearest, on=on, resolve=resolve, **kwds) - - -class SingleSelectionConfig(VegaLiteSchema): - """SingleSelectionConfig schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - bind : anyOf(:class:`Binding`, Mapping(required=[]), :class:`LegendBinding`) - 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. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. Can be a `Event Stream - `__ or ``false`` to disable. - - **Default value:** ``dblclick``. - - **See also:** `clear `__ - documentation. - empty : enum('all', 'none') - By default, ``all`` data values are considered to lie within an empty selection. - When set to ``none``, empty selections contain no data values. - 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:** `encodings `__ - 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:** `fields `__ - documentation. - init : :class:`SelectionInitMapping` - Initialize the selection with a mapping between `projected channels or field names - `__ and initial values. - - **See also:** `init `__ - 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. - - **See also:** `nearest `__ - 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 - `__. - 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. - - **See also:** `resolve - `__ documentation. - """ - _schema = {'$ref': '#/definitions/SingleSelectionConfig'} - - def __init__(self, bind=Undefined, clear=Undefined, empty=Undefined, encodings=Undefined, - fields=Undefined, init=Undefined, nearest=Undefined, on=Undefined, resolve=Undefined, - **kwds): - super(SingleSelectionConfig, self).__init__(bind=bind, clear=clear, empty=empty, - encodings=encodings, fields=fields, init=init, - nearest=nearest, on=on, resolve=resolve, **kwds) - - -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. - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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 - - Attributes - ---------- - - 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): - """ConcatSpecGenericSpec schema wrapper - - Mapping(required=[concat]) - Base interface for a generalized concatenation specification. - - Attributes - ---------- - - 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): - """FacetSpec schema wrapper - - Mapping(required=[facet, spec]) - Base interface for a facet specification. - - Attributes - ---------- - - facet : anyOf(:class:`FacetFieldDefFieldName`, :class:`FacetMappingFieldName`) - 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(NormalizedSpec, Spec): - """FacetedUnitSpec schema wrapper - - Mapping(required=[mark]) - Unit spec that can have a composite mark and row or column channels (shorthand for a facet - spec). - - Attributes - ---------- - - 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. - 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. - selection : Mapping(required=[]) - A key-value mapping between selection names and definitions. - 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, projection=Undefined, resolve=Undefined, selection=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, projection=projection, - resolve=resolve, selection=selection, spacing=spacing, - title=title, transform=transform, view=view, width=width, - **kwds) - - -class HConcatSpecGenericSpec(Spec): - """HConcatSpecGenericSpec schema wrapper - - Mapping(required=[hconcat]) - Base interface for a horizontal concatenation specification. - - Attributes - ---------- - - 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(NormalizedSpec, Spec): - """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. - - Attributes - ---------- - - 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(NormalizedSpec, Spec): - """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]) - - Attributes - ---------- - - 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:`UnitSpec`) - 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. - - Attributes - ---------- - - 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:`Spec` - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - step : float - The size (width/height) per discrete step. - """ - _schema = {'$ref': '#/definitions/Step'} - - def __init__(self, step=Undefined, **kwds): - super(Step, self).__init__(step=step, **kwds) - - -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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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, band=Undefined, bin=Undefined, field=Undefined, - format=Undefined, formatType=Undefined, labelExpr=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(StringFieldDef, self).__init__(aggregate=aggregate, band=band, bin=bin, field=field, - format=format, formatType=formatType, labelExpr=labelExpr, - timeUnit=timeUnit, title=title, type=type, **kwds) - - -class StringFieldDefWithCondition(VegaLiteSchema): - """StringFieldDefWithCondition schema wrapper - - Mapping(required=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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, band=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, labelExpr=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(StringFieldDefWithCondition, self).__init__(aggregate=aggregate, band=band, bin=bin, - condition=condition, field=field, - format=format, formatType=formatType, - labelExpr=labelExpr, timeUnit=timeUnit, - title=title, type=type, **kwds) - - -class StringValueDefWithCondition(VegaLiteSchema): - """StringValueDefWithCondition schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, - :class:`ConditionalValueDefstringnullExprRef`, - List(:class:`ConditionalValueDefstringnullExprRef`)) - A field definition or one or more value definition(s) with a selection 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=[]) - - Attributes - ---------- - - 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=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - condition : anyOf(:class:`ConditionalValueDefTextExprRef`, - List(:class:`ConditionalValueDefTextExprRef`)) - One or more value definition(s) with `a selection 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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, band=Undefined, condition=Undefined, datum=Undefined, format=Undefined, - formatType=Undefined, labelExpr=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionStringDatumDefText, self).__init__(band=band, - condition=condition, - datum=datum, format=format, - formatType=formatType, - labelExpr=labelExpr, - type=type, **kwds) - - -class FieldOrDatumDefWithConditionStringFieldDefText(TextDef): - """FieldOrDatumDefWithConditionStringFieldDefText schema wrapper - - Mapping(required=[]) - A FieldDef with Condition :raw-html:`` { condition: {value: ...}, field: - ..., ... } - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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 selection 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:`Dictunknown`) - 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``. - labelExpr : string - `Vega expression `__ for customizing - labels text. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - 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, band=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, labelExpr=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionStringFieldDefText, self).__init__(aggregate=aggregate, - band=band, bin=bin, - condition=condition, - field=field, format=format, - formatType=formatType, - labelExpr=labelExpr, - 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=[]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - ariaRole : anyOf(string, :class:`ExprRef`) - - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - - aspect : anyOf(boolean, :class:`ExprRef`) - - 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`) - - 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`) - - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - - description : anyOf(string, :class:`ExprRef`) - - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - ellipsis : anyOf(string, :class:`ExprRef`) - - endAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - height : anyOf(float, :class:`ExprRef`) - - href : anyOf(:class:`URI`, :class:`ExprRef`) - - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - - 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`) - - lineBreak : anyOf(string, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - 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``. - padAngle : anyOf(float, :class:`ExprRef`) - - 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. - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - - 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`) - - startAngle : anyOf(float, :class:`ExprRef`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOffset : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - tension : anyOf(float, :class:`ExprRef`) - - text : anyOf(:class:`Text`, :class:`ExprRef`) - - 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`` - timeUnitBand : 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. - 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. - 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`) - - width : anyOf(float, :class:`ExprRef`) - - 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, timeUnitBand=Undefined, - timeUnitBandPosition=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, timeUnitBand=timeUnitBand, - timeUnitBandPosition=timeUnitBandPosition, 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]) - - Attributes - ---------- - - 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 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=[]) - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - align : :class:`Align` - Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or - ``"right"``. - anchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - - angle : anyOf(float, :class:`ExprRef`) - - aria : anyOf(boolean, :class:`ExprRef`) - - 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`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - font : anyOf(string, :class:`ExprRef`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - frame : anyOf(anyOf(:class:`TitleFrame`, string), :class:`ExprRef`) - - limit : anyOf(float, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - offset : anyOf(float, :class:`ExprRef`) - - orient : anyOf(:class:`TitleOrient`, :class:`ExprRef`) - - subtitleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - - subtitleFont : anyOf(string, :class:`ExprRef`) - - subtitleFontSize : anyOf(float, :class:`ExprRef`) - - subtitleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - subtitleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - subtitleLineHeight : anyOf(float, :class:`ExprRef`) - - subtitlePadding : anyOf(float, :class:`ExprRef`) - - zindex : anyOf(float, :class:`ExprRef`) - - """ - _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]) - - Attributes - ---------- - - 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`) - - aria : anyOf(boolean, :class:`ExprRef`) - - 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`) - - dx : anyOf(float, :class:`ExprRef`) - - dy : anyOf(float, :class:`ExprRef`) - - font : anyOf(string, :class:`ExprRef`) - - fontSize : anyOf(float, :class:`ExprRef`) - - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - frame : anyOf(anyOf(:class:`TitleFrame`, string), :class:`ExprRef`) - - limit : anyOf(float, :class:`ExprRef`) - - lineHeight : anyOf(float, :class:`ExprRef`) - - offset : anyOf(float, :class:`ExprRef`) - - orient : anyOf(:class:`TitleOrient`, :class:`ExprRef`) - - 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`) - - subtitleFont : anyOf(string, :class:`ExprRef`) - - subtitleFontSize : anyOf(float, :class:`ExprRef`) - - subtitleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - - subtitleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - - subtitleLineHeight : anyOf(float, :class:`ExprRef`) - - subtitlePadding : anyOf(float, :class:`ExprRef`) - - 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]) - - Attributes - ---------- - - content : enum('encoding', 'data') - - """ - _schema = {'$ref': '#/definitions/TooltipContent'} - - def __init__(self, content=Undefined, **kwds): - super(TooltipContent, self).__init__(content=content, **kwds) - - -class TopLevelSpec(VegaLiteSchema): - """TopLevelSpec schema wrapper - - anyOf(:class:`TopLevelUnitSpec`, :class:`TopLevelFacetSpec`, :class:`TopLevelLayerSpec`, - :class:`TopLevelRepeatSpec`, :class:`TopLevelNormalizedConcatSpecGenericSpec`, - :class:`TopLevelNormalizedVConcatSpecGenericSpec`, - :class:`TopLevelNormalizedHConcatSpecGenericSpec`) - 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 TopLevelFacetSpec(TopLevelSpec): - """TopLevelFacetSpec schema wrapper - - Mapping(required=[data, facet, spec]) - - Attributes - ---------- - - 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:`Parameter`) - Dynamic variables 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:`Dictunknown` - 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/v4.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 TopLevelLayerSpec(TopLevelSpec): - """TopLevelLayerSpec schema wrapper - - Mapping(required=[layer]) - - Attributes - ---------- - - 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:`Parameter`) - Dynamic variables 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:`Dictunknown` - 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/v4.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 TopLevelNormalizedConcatSpecGenericSpec(TopLevelSpec): - """TopLevelNormalizedConcatSpecGenericSpec schema wrapper - - Mapping(required=[concat]) - - Attributes - ---------- - - concat : List(:class:`NormalizedSpec`) - 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:`Parameter`) - Dynamic variables 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:`Dictunknown` - 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/v4.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelNormalizedConcatSpec'} - - 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(TopLevelNormalizedConcatSpecGenericSpec, 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 TopLevelNormalizedHConcatSpecGenericSpec(TopLevelSpec): - """TopLevelNormalizedHConcatSpecGenericSpec schema wrapper - - Mapping(required=[hconcat]) - - Attributes - ---------- - - hconcat : List(:class:`NormalizedSpec`) - 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:`Parameter`) - Dynamic variables 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:`Dictunknown` - 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/v4.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelNormalizedHConcatSpec'} - - 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(TopLevelNormalizedHConcatSpecGenericSpec, 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 TopLevelNormalizedVConcatSpecGenericSpec(TopLevelSpec): - """TopLevelNormalizedVConcatSpecGenericSpec schema wrapper - - Mapping(required=[vconcat]) - - Attributes - ---------- - - vconcat : List(:class:`NormalizedSpec`) - 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:`Parameter`) - Dynamic variables 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:`Dictunknown` - 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/v4.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelNormalizedVConcatSpec'} - - 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(TopLevelNormalizedVConcatSpecGenericSpec, 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 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]) - - Attributes - ---------- - - 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:`Parameter`) - Dynamic variables that parameterize a visualization. - 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. - selection : Mapping(required=[]) - A key-value mapping between selection names and definitions. - 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:`Dictunknown` - 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/v4.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, selection=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, - selection=selection, spacing=spacing, title=title, - transform=transform, usermeta=usermeta, view=view, - width=width, **kwds) - - -class TopoDataFormat(DataFormat): - """TopoDataFormat schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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, 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`, :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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - fold : List(:class:`FieldName`) - An array of data fields indicating the properties to fold. - as : List([:class:`FieldName`, :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]) - - Attributes - ---------- - - 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), 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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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`, :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]) - - Attributes - ---------- - - lookup : string - Key in primary data source. - default : string - 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]) - - Attributes - ---------- - - 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 : string - 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]) - - Attributes - ---------- - - 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`, :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]) - - Attributes - ---------- - - 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, 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`, :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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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`, :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]) - - Attributes - ---------- - - 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. - - Attributes - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - band : float - For rect-based marks ( ``rect``, ``bar``, and ``image`` ), mark size relative to - bandwidth of `band scales - `__, bins or time units. If - set to ``1``, the mark size is set to the bandwidth, the bin interval, or the time - unit interval. If set to ``0.5``, the mark size is half of the bandwidth or the time - unit interval. - - For other marks, relative position on a band of a stacked, binned, time unit or band - scale. If set to ``0``, the marks will be positioned at the beginning of the band. - If set to ``0.5``, the marks will be positioned in the middle of the band. - 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, band=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(TypedFieldDef, self).__init__(aggregate=aggregate, band=band, 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]) - A unit specification, which can contain either `primitive marks or composite marks - `__. - - Attributes - ---------- - - 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`) - **Deprecated:** Please avoid using width in a unit spec that's a part of a layer - spec. - name : string - Name of the visualization for later reference. - 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. - selection : Mapping(required=[]) - A key-value mapping between selection names and definitions. - 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` - **Deprecated:** Please avoid using width in a unit spec that's a part of a layer - spec. - width : anyOf(float, string, :class:`Step`) - **Deprecated:** Please avoid using width in a unit spec that's a part of a layer - spec. - """ - _schema = {'$ref': '#/definitions/UnitSpec'} - - def __init__(self, mark=Undefined, data=Undefined, description=Undefined, encoding=Undefined, - height=Undefined, name=Undefined, projection=Undefined, selection=Undefined, - title=Undefined, transform=Undefined, view=Undefined, width=Undefined, **kwds): - super(UnitSpec, self).__init__(mark=mark, data=data, description=description, encoding=encoding, - height=height, name=name, projection=projection, - selection=selection, title=title, transform=transform, view=view, - width=width, **kwds) - - -class UnitSpecWithFrame(VegaLiteSchema): - """UnitSpecWithFrame schema wrapper - - Mapping(required=[mark]) - - Attributes - ---------- - - 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. - 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. - selection : Mapping(required=[]) - A key-value mapping between selection names and definitions. - 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, projection=Undefined, selection=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, - projection=projection, selection=selection, title=title, - transform=transform, view=view, width=width, **kwds) - - -class UrlData(DataSource): - """UrlData schema wrapper - - Mapping(required=[url]) - - Attributes - ---------- - - 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): - """VConcatSpecGenericSpec schema wrapper - - Mapping(required=[vconcat]) - Base interface for a vertical concatenation specification. - - Attributes - ---------- - - 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=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, - :class:`ConditionalValueDefGradientstringnullExprRef`, - List(:class:`ConditionalValueDefGradientstringnullExprRef`)) - A field definition or one or more value definition(s) with a selection 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=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDefTypeForShape`, - :class:`ConditionalValueDefstringnullExprRef`, - List(:class:`ConditionalValueDefstringnullExprRef`)) - A field definition or one or more value definition(s) with a selection 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=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, - :class:`ConditionalValueDefnumberExprRef`, List(:class:`ConditionalValueDefnumberExprRef`)) - A field definition or one or more value definition(s) with a selection 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=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, - :class:`ConditionalValueDefnumberArrayExprRef`, - List(:class:`ConditionalValueDefnumberArrayExprRef`)) - A field definition or one or more value definition(s) with a selection 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=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, - :class:`ConditionalValueDefstringnullExprRef`, - List(:class:`ConditionalValueDefstringnullExprRef`)) - A field definition or one or more value definition(s) with a selection 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=[]) - - Attributes - ---------- - - condition : anyOf(:class:`ConditionalStringFieldDef`, - :class:`ConditionalValueDefTextExprRef`, List(:class:`ConditionalValueDefTextExprRef`)) - A field definition or one or more value definition(s) with a selection 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(VegaLiteSchema): - """ValueDefnumber schema wrapper - - Mapping(required=[value]) - Definition object for a constant value (primitive value or gradient definition) of an - encoding channel. - - Attributes - ---------- - - 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 ValueDefnumberExprRef(VegaLiteSchema): - """ValueDefnumberExprRef schema wrapper - - Mapping(required=[value]) - Definition object for a constant value (primitive value or gradient definition) of an - encoding channel. - - Attributes - ---------- - - 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/ValueDef<(number|ExprRef)>'} - - def __init__(self, value=Undefined, **kwds): - super(ValueDefnumberExprRef, 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. - - Attributes - ---------- - - 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 Vector2DateTime(SelectionInitInterval): - """Vector2DateTime schema wrapper - - List([:class:`DateTime`, :class:`DateTime`]) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2DateTime, self).__init__(*args) - - -class Vector2Vector2number(VegaLiteSchema): - """Vector2Vector2number schema wrapper - - List([:class:`Vector2number`, :class:`Vector2number`]) - """ - _schema = {'$ref': '#/definitions/Vector2>'} - - def __init__(self, *args): - super(Vector2Vector2number, self).__init__(*args) - - -class Vector2boolean(SelectionInitInterval): - """Vector2boolean schema wrapper - - List([boolean, boolean]) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2boolean, self).__init__(*args) - - -class Vector2number(SelectionInitInterval): - """Vector2number schema wrapper - - List([float, float]) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2number, self).__init__(*args) - - -class Vector2string(SelectionInitInterval): - """Vector2string schema wrapper - - List([string, string]) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2string, self).__init__(*args) - - -class Vector3number(VegaLiteSchema): - """Vector3number schema wrapper - - List([float, float, float]) - """ - _schema = {'$ref': '#/definitions/Vector3'} - - def __init__(self, *args): - super(Vector3number, self).__init__(*args) - - -class ViewBackground(VegaLiteSchema): - """ViewBackground schema wrapper - - Mapping(required=[]) - - Attributes - ---------- - - cornerRadius : anyOf(float, :class:`ExprRef`) - - 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`) - - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - 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=[]) - - Attributes - ---------- - - 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`) - - 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`) - - height : float - Default height - - **Deprecated:** Since Vega-Lite 4.0. Please use continuousHeight and discreteHeight - instead. - 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`) - - strokeDash : anyOf(List(float), :class:`ExprRef`) - - strokeDashOffset : anyOf(float, :class:`ExprRef`) - - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - - strokeOpacity : anyOf(float, :class:`ExprRef`) - - strokeWidth : anyOf(float, :class:`ExprRef`) - - width : float - Default width - - **Deprecated:** Since Vega-Lite 4.0. Please use continuousWidth and discreteWidth - instead. - """ - _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, height=Undefined, - opacity=Undefined, step=Undefined, stroke=Undefined, strokeCap=Undefined, - strokeDash=Undefined, strokeDashOffset=Undefined, strokeJoin=Undefined, - strokeMiterLimit=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - width=Undefined, **kwds): - super(ViewConfig, self).__init__(clip=clip, continuousHeight=continuousHeight, - continuousWidth=continuousWidth, cornerRadius=cornerRadius, - cursor=cursor, discreteHeight=discreteHeight, - discreteWidth=discreteWidth, fill=fill, - fillOpacity=fillOpacity, height=height, opacity=opacity, - step=step, stroke=stroke, strokeCap=strokeCap, - strokeDash=strokeDash, strokeDashOffset=strokeDashOffset, - strokeJoin=strokeJoin, strokeMiterLimit=strokeMiterLimit, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - width=width, **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]) - - Attributes - ---------- - - 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]) - - Attributes - ---------- - - 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/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/data/replace_dataset.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/data/replace_dataset.py deleted file mode 100644 index 5aac2ba96bee0a8bb65f4c9e56fa0b17248ee1d9..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/data/replace_dataset.py +++ /dev/null @@ -1,36 +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 . import BaseWrapperDataset - - -class ReplaceDataset(BaseWrapperDataset): - """Replaces tokens found in the dataset by a specified replacement token - - Args: - dataset (~torch.utils.data.Dataset): dataset to replace tokens in - replace_map(Dictionary[int,int]): map of token to replace -> replacement token - offsets (List[int]): do not replace tokens before (from left if pos, right if neg) this offset. should be - as many as the number of objects returned by the underlying dataset __getitem__ method. - """ - - def __init__(self, dataset, replace_map, offsets): - super().__init__(dataset) - assert len(replace_map) > 0 - self.replace_map = replace_map - self.offsets = offsets - - def __getitem__(self, index): - item = self.dataset[index] - is_tuple = isinstance(item, tuple) - srcs = item if is_tuple else [item] - - for offset, src in zip(self.offsets, srcs): - for k, v in self.replace_map.items(): - src_off = src[offset:] if offset >= 0 else src[:offset] - src_off.masked_fill_(src_off == k, v) - - item = srcs if is_tuple else srcs[0] - return item diff --git a/spaces/asigalov61/Allegro-Music-Transformer/app.py b/spaces/asigalov61/Allegro-Music-Transformer/app.py deleted file mode 100644 index b8528a68fdb3ee1c751535b2e9b9e41676b6ff52..0000000000000000000000000000000000000000 --- a/spaces/asigalov61/Allegro-Music-Transformer/app.py +++ /dev/null @@ -1,270 +0,0 @@ -import argparse -import glob -import json -import os.path - -import time -import datetime -from pytz import timezone - -import torch -import torch.nn.functional as F - -import gradio as gr - -from x_transformer import * -import tqdm - -from midi_synthesizer import synthesis -import TMIDIX - -import matplotlib.pyplot as plt - -in_space = os.getenv("SYSTEM") == "spaces" - -# ================================================================================================= - -@torch.no_grad() -def GenerateMIDI(num_tok, idrums, iinstr): - print('=' * 70) - print('Req start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT))) - start_time = time.time() - - print('-' * 70) - print('Req num tok:', num_tok) - print('Req instr:', iinstr) - print('Drums:', idrums) - print('-' * 70) - - if idrums: - drums = 3074 - else: - drums = 3073 - - instruments_list = ["Piano", "Guitar", "Bass", "Violin", "Cello", "Harp", "Trumpet", "Sax", "Flute", 'Drums', - "Choir", "Organ"] - first_note_instrument_number = instruments_list.index(iinstr) - - start_tokens = [3087, drums, 3075 + first_note_instrument_number] - - print('Selected Improv sequence:') - print(start_tokens) - print('-' * 70) - - output_signature = 'Allegro Music Transformer' - output_file_name = 'Allegro-Music-Transformer-Music-Composition' - track_name = 'Project Los Angeles' - list_of_MIDI_patches = [0, 24, 32, 40, 42, 46, 56, 71, 73, 0, 53, 19, 0, 0, 0, 0] - number_of_ticks_per_quarter = 500 - text_encoding = 'ISO-8859-1' - - output_header = [number_of_ticks_per_quarter, - [['track_name', 0, bytes(output_signature, text_encoding)]]] - - patch_list = [['patch_change', 0, 0, list_of_MIDI_patches[0]], - ['patch_change', 0, 1, list_of_MIDI_patches[1]], - ['patch_change', 0, 2, list_of_MIDI_patches[2]], - ['patch_change', 0, 3, list_of_MIDI_patches[3]], - ['patch_change', 0, 4, list_of_MIDI_patches[4]], - ['patch_change', 0, 5, list_of_MIDI_patches[5]], - ['patch_change', 0, 6, list_of_MIDI_patches[6]], - ['patch_change', 0, 7, list_of_MIDI_patches[7]], - ['patch_change', 0, 8, list_of_MIDI_patches[8]], - ['patch_change', 0, 9, list_of_MIDI_patches[9]], - ['patch_change', 0, 10, list_of_MIDI_patches[10]], - ['patch_change', 0, 11, list_of_MIDI_patches[11]], - ['patch_change', 0, 12, list_of_MIDI_patches[12]], - ['patch_change', 0, 13, list_of_MIDI_patches[13]], - ['patch_change', 0, 14, list_of_MIDI_patches[14]], - ['patch_change', 0, 15, list_of_MIDI_patches[15]], - ['track_name', 0, bytes(track_name, text_encoding)]] - - output = output_header + [patch_list] - - yield output, None, None, [create_msg("visualizer_clear", None)] - - outy = start_tokens - - ctime = 0 - dur = 0 - vel = 90 - pitch = 0 - channel = 0 - - for i in range(max(1, min(512, num_tok))): - - inp = torch.LongTensor([outy]).cpu() - - out = model.module.generate(inp, - 1, - temperature=0.9, - return_prime=False, - verbose=False) - - out0 = out[0].tolist() - outy.extend(out0) - - ss1 = out0[0] - - if 0 < ss1 < 256: - ctime += ss1 * 8 - - if 256 <= ss1 < 1280: - dur = ((ss1 - 256) // 8) * 32 - vel = (((ss1 - 256) % 8) + 1) * 15 - - if 1280 <= ss1 < 2816: - channel = (ss1 - 1280) // 128 - pitch = (ss1 - 1280) % 128 - event = ['note', ctime, dur, channel, pitch, vel] - output[-1].append(event) - - yield output, None, None, [create_msg("visualizer_append", event), create_msg("progress", [i + 1, num_tok])] - - midi_data = TMIDIX.score2midi(output, text_encoding) - - with open(f"Allegro-Music-Transformer-Music-Composition.mid", 'wb') as f: - f.write(midi_data) - - audio = synthesis(TMIDIX.score2opus(output), 'SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2') - - print('Sample INTs', outy[:16]) - print('-' * 70) - print('Last generated MIDI event', output[2][-1]) - print('-' * 70) - print('Req end time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT))) - print('-' * 70) - print('Req execution time:', (time.time() - start_time), 'sec') - - yield output, "Allegro-Music-Transformer-Music-Composition.mid", (44100, audio), [ - create_msg("visualizer_end", None)] - - -def cancel_run(mid_seq): - if mid_seq is None: - return None, None, None - text_encoding = 'ISO-8859-1' - midi_data = TMIDIX.score2midi(mid_seq, text_encoding) - - with open(f"Allegro-Music-Transformer-Music-Composition.mid", 'wb') as f: - f.write(midi_data) - - audio = synthesis(TMIDIX.score2opus(mid_seq), 'SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2') - - yield "Allegro-Music-Transformer-Music-Composition.mid", (44100, audio), [ - create_msg("visualizer_end", None)] - - -# ================================================================================================= - -def load_javascript(dir="javascript"): - scripts_list = glob.glob(f"{dir}/*.js") - javascript = "" - for path in scripts_list: - with open(path, "r", encoding="utf8") as jsfile: - javascript += f"\n" - template_response_ori = gr.routes.templates.TemplateResponse - - def template_response(*args, **kwargs): - res = template_response_ori(*args, **kwargs) - res.body = res.body.replace( - b'', f'{javascript}'.encode("utf8")) - res.init_headers() - return res - - gr.routes.templates.TemplateResponse = template_response - - -class JSMsgReceiver(gr.HTML): - - def __init__(self, **kwargs): - super().__init__(elem_id="msg_receiver", visible=False, **kwargs) - - def postprocess(self, y): - if y: - y = f"

{json.dumps(y)}

" - return super().postprocess(y) - - def get_block_name(self) -> str: - return "html" - - -def create_msg(name, data): - return {"name": name, "data": data} - - -if __name__ == "__main__": - - PDT = timezone('US/Pacific') - - print('=' * 70) - print('App start time: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now(PDT))) - print('=' * 70) - - parser = argparse.ArgumentParser() - parser.add_argument("--share", action="store_true", default=False, help="share gradio app") - parser.add_argument("--port", type=int, default=7860, help="gradio server port") - opt = parser.parse_args() - - print('Loading model...') - - SEQ_LEN = 2048 - - # instantiate the model - - model = TransformerWrapper( - num_tokens=3088, - max_seq_len=SEQ_LEN, - attn_layers=Decoder(dim=1024, depth=16, heads=8) - ) - - model = AutoregressiveWrapper(model) - - model = torch.nn.DataParallel(model) - - model.cpu() - print('=' * 70) - - print('Loading model checkpoint...') - - model.load_state_dict( - torch.load('Allegro_Music_Transformer_Tiny_Trained_Model_80000_steps_0.9457_loss_0.7443_acc.pth', - map_location='cpu')) - print('=' * 70) - - model.eval() - - print('Done!') - print('=' * 70) - - load_javascript() - app = gr.Blocks() - with app: - gr.Markdown("

Allegro Music Transformer

") - gr.Markdown( - "![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.Allegro-Music-Transformer&style=flat)\n\n" - "Full-attention multi-instrumental music transformer featuring asymmetrical encoding with octo-velocity, and chords counters tokens, optimized for speed and performance\n\n" - "Check out [Allegro Music Transformer](https://github.com/asigalov61/Allegro-Music-Transformer) on GitHub!\n\n" - "Special thanks go out to [SkyTNT](https://github.com/SkyTNT/midi-model) for fantastic FluidSynth Synthesizer and MIDI Visualizer code\n\n" - "[Open In Colab]" - "(https://colab.research.google.com/github/asigalov61/Allegro-Music-Transformer/blob/main/Allegro_Music_Transformer_Composer.ipynb)" - " for faster execution and endless generation" - ) - js_msg = JSMsgReceiver() - input_drums = gr.Checkbox(label="Add Drums", value=False, info="Add drums to the composition") - input_instrument = gr.Radio( - ["Piano", "Guitar", "Bass", "Violin", "Cello", "Harp", "Trumpet", "Sax", "Flute", "Choir", "Organ"], - value="Piano", label="Lead Instrument Controls", info="Desired lead instrument") - input_num_tokens = gr.Slider(16, 512, value=256, label="Number of Tokens", info="Number of tokens to generate") - run_btn = gr.Button("generate", variant="primary") - interrupt_btn = gr.Button("interrupt") - - output_midi_seq = gr.Variable() - output_midi_visualizer = gr.HTML(elem_id="midi_visualizer_container") - output_audio = gr.Audio(label="output audio", format="mp3", elem_id="midi_audio") - output_midi = gr.File(label="output midi", file_types=[".mid"]) - run_event = run_btn.click(GenerateMIDI, [input_num_tokens, input_drums, input_instrument], - [output_midi_seq, output_midi, output_audio, js_msg]) - interrupt_btn.click(cancel_run, output_midi_seq, [output_midi, output_audio, js_msg], - cancels=run_event, queue=False) - app.queue(concurrency_count=1).launch(server_port=opt.port, share=opt.share, inbrowser=True) \ No newline at end of file diff --git a/spaces/autosummproject/autosumm/translation/__init__.py b/spaces/autosummproject/autosumm/translation/__init__.py deleted file mode 100644 index fc095d6b5e780eb1489b577fc533d494f39ae638..0000000000000000000000000000000000000000 --- a/spaces/autosummproject/autosumm/translation/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .translation import translate \ No newline at end of file diff --git a/spaces/awacke1/Bloom.Generative.Writer/app.py b/spaces/awacke1/Bloom.Generative.Writer/app.py deleted file mode 100644 index 5edd03b6d3e5c4887c7f4c5796c68e7f518b02d3..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Bloom.Generative.Writer/app.py +++ /dev/null @@ -1,58 +0,0 @@ -import streamlit as st -from templates.Templates import PromptTemplate -from generators.title_to_abstract import title_to_abstract_generator -from generators.topic_to_abstract import topic_to_abstract_generator - -from flask_app import generate - - -prompt = PromptTemplate() - -result_text = "" - -st.title('Scientific Paper Abstract Writer') - - -col_1, col_2 = st.columns(2) - -with col_1: - st.markdown( - """ - This is an **AI powered** tool that will help you write an abstract for your scientific paper. - - There are two ways you can generate the abstract: - - 1. **Title to Abstract** - This will generate an abstract based on the title of your paper. - - 2. **Topic to Abstract** - This will generate an abstract based on the topic of your paper. - """ - ) -with col_2: - option = st.radio('Please select one', - ('Title to Abstract', 'Topic to Abstract')) - - st.write('You selected:', option) - - if option == 'Title to Abstract': - title = st.text_area( - 'Please input the title of the paper. ' - 'Five or more words are suggested for best results. ') - if st.button('Generate'): - with st.spinner('Generating...'): - result = generate({'title': title}, 'title') - st.success('Generated abstract: ') - result_text = result['result'] - else: - topic = st.text_area( - 'Please input the topic of the paper. Example: Topic_1 , Topic_2, Topic_3 ') - list_topic = topic.split(',') - if st.button('Generate'): - with st.spinner('Generating...'): - result = generate({'topic': list_topic}, 'topic') - st.success('Generated abstract: ') - result_text = result['result'] - -st.write(result_text) - - -st.markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=Ghostwriter-Bloom)") \ No newline at end of file diff --git a/spaces/awacke1/DockerGoFlanT5/static/style.css b/spaces/awacke1/DockerGoFlanT5/static/style.css deleted file mode 100644 index 7b50df8f6904c75f560224034d8aadd76656c6f8..0000000000000000000000000000000000000000 --- a/spaces/awacke1/DockerGoFlanT5/static/style.css +++ /dev/null @@ -1,45 +0,0 @@ -body { - --text: hsl(0 0% 15%); - padding: 2.5rem; - font-family: sans-serif; - color: var(--text); -} - -body.dark-theme { - --text: hsl(0 0% 90%); - background-color: hsl(223 39% 7%); -} - -main { - max-width: 80rem; - text-align: center; -} - -section { - display: flex; - flex-direction: column; - align-items: center; -} - -a { - color: var(--text); -} - -form { - width: 30rem; - margin: 0 auto; -} - -input { - width: 100%; -} - -button { - cursor: pointer; -} - -.text-gen-output { - min-height: 1.2rem; - margin: 1rem; - border: 0.5px solid grey; -} diff --git a/spaces/awacke1/StreamlitMapBoxCityNames/app.py b/spaces/awacke1/StreamlitMapBoxCityNames/app.py deleted file mode 100644 index e0a2760033081e2de8e48e0678397315c38f9b2e..0000000000000000000000000000000000000000 --- a/spaces/awacke1/StreamlitMapBoxCityNames/app.py +++ /dev/null @@ -1,54 +0,0 @@ -#write a streamlit map viewer that can show the detail and search for any city in the united states. - -import streamlit as st -import pandas as pd -import numpy as np -import pydeck as pdk - -DATA_URL = ( -"uscities.csv" -) - -# Load data into dataframe -df = pd.read_csv(DATA_URL) - -st.title("Map Viewer") - -# Create a text element and let the reader know the data is loading. -st.text("Loading data...") -st.text("Search for any city in the United States:") - -# Get the user's search query -search_query = st.text_input(label="City Name", value="") - -# Filter the dataframe -if search_query != "": - df = df[df["city"].str.contains(search_query) == True] - -# Create a subheader -st.subheader("City Detail") - -# Show the data -st.write(df) - -st.pydeck_chart(pdk.Deck( - map_style="mapbox://styles/mapbox/dark-v9", - initial_view_state={ - "lat": df["lat"].mean(), - "lng": df["lng"].mean(), - "zoom": 4, - "pitch": 0, - }, - layers=[ - pdk.Layer( - "HexagonLayer", - data=df, - get_position=["lng", "lat"], - radius=100, - elevation_scale=4, - elevation_range=[0, 1000], - pickable=True, - extruded=True, - ), - ], -)) \ No newline at end of file diff --git a/spaces/bcg-unet/demo/bcgrun_web.py b/spaces/bcg-unet/demo/bcgrun_web.py deleted file mode 100644 index 7ceacbd2b5ae8bab648b13eb88572b0d09a66261..0000000000000000000000000000000000000000 --- a/spaces/bcg-unet/demo/bcgrun_web.py +++ /dev/null @@ -1,127 +0,0 @@ -import numpy as np -from scipy.io import savemat -import h5py -from bcgunet import bcgunet -import platform -import os -import time -import os -import gradio as gr -import matplotlib -import matplotlib.pyplot as plt - -matplotlib.use("agg") - -dir = os.path.dirname(os.path.realpath(__file__)) + "/tmp" -os.makedirs(dir, exist_ok=True) - - -def run( - files: list[bytes], - lr: float, - winsec: int, - iters: int, - onecycle: bool, - ecg: str, - bce: str, - eeg: str, -) -> tuple[list[str], str]: - task = os.path.join(dir, str(int(time.time()))) - os.makedirs(task) - - outputs = [] - - for i, file in enumerate(files): - input = os.path.join(task, str(i) + ".mat") - with open(input, "wb") as o: - o.write(file) - - output = os.path.join(task, str(i) + "_clean.mat") - - mat = h5py.File(input, "r") - ECG = np.array(mat[ecg]).flatten() - EEG = np.array(mat[bce]).T - - EEG_unet = bcgunet.run( - EEG, - ECG, - iter_num=iters, - winsize_sec=winsec, - lr=lr, - onecycle=onecycle, - ) - result = dict() - result[eeg] = EEG_unet - - savemat(output, result, do_compression=True) - outputs.append(output) - - if i == 0: - plt.figure(figsize=(12, 6), dpi=300) - plt.plot(EEG[19, :10000], "b.-", label="Orig EEG") - plt.plot(EEG_unet[19, :10000], "g.-", label="U-Net") - plt.legend() - plt.title("BCG Unet") - plt.xlabel("Time (samples)") - plot = os.path.join(task, str(i) + ".png") - plt.savefig(plot) - - return outputs, plot - - -def main(): - app = gr.Interface( - title="BCG Unet", - description="BCGunet: Suppressing BCG artifacts on EEG collected inside an MRI scanner", - fn=run, - inputs=[ - gr.File( - label="Input Files (.mat)", - type="binary", - file_types=["mat"], - file_count=["multiple", "directory"], - ), - gr.Slider( - label="Learning Rate", minimum=1e-5, maximum=1e-1, step=1e-5, value=1e-3 - ), - gr.Slider( - label="Window Size (seconds)", minimum=1, maximum=10, step=1, value=2 - ), - gr.Slider( - label="Number of Iterations", - minimum=1000, - maximum=10000, - step=1000, - value=5000, - ), - gr.Checkbox( - label="One Cycle Scheduler", - value=True, - ), - gr.Textbox( - label="Variable name for ECG (input)", - value="ECG", - ), - gr.Textbox( - label="Variable name for BCG corropted EEG (input)", - value="EEG_before_bcg", - ), - gr.Textbox( - label="Variable name for clean EEG (output)", - value="EEG_clean", - ), - ], - outputs=[ - gr.File(label="Output File", file_count="multiple"), - gr.Image(label="Output Image", type="filepath"), - ], - allow_flagging="never", - ) - - app.launch() - - -if __name__ == "__main__": - main() - if platform.system() == "Windows": - os.system("pause") diff --git a/spaces/beihai/PDF-Table-Extractor/.history/app_20220621095327.py b/spaces/beihai/PDF-Table-Extractor/.history/app_20220621095327.py deleted file mode 100644 index 407b66c64af6c7060daf7608740b1ee3ec3c632a..0000000000000000000000000000000000000000 --- a/spaces/beihai/PDF-Table-Extractor/.history/app_20220621095327.py +++ /dev/null @@ -1,40 +0,0 @@ -#-*- coding : utf-8-*- -import base64 -from subprocess import STDOUT -import streamlit as st -import pandas as pd -import camelot as cam # extracting tables from PDFs - -st.title("PDF Table Extractor") - -input_pdf = st.file_uploader(label = "", type = 'pdf') - -page_number = st.text_input("请填写表格所在PDF页码,eg: 3", value = 1) -background = st.selectbox("表格线条是否隐藏",(True, False)) -if input_pdf is not None: - # byte object into a PDF file - with open("input.pdf", "wb") as f: - base64_pdf = base64.b64encode(input_pdf.read()).decode('utf-8') - f.write(base64.b64decode(base64_pdf)) - f.close() - - # read the pdf and parse it using stream - tables = cam.read_pdf("input.pdf", pages=page_number, process_background=background) - result = pd.ExcelWriter('result.xlsx', engine='xlsxwriter') - tables[0].to_excel(result,index=False) - # for i in range(0,len(tables)): - # table = tables[i].df - # sheetname = str(i) - # table.to_excel(result, sheetname,index=False) - - with open('result.xlsx','rb') as f: - st.download_button('提取完成,点击下载!', f,file_name='result.xlsx',mime="application/vnd.ms-excel") - - tables_all= cam.read_pdf("input.pdf", pages=all, process_background=background) - result_all = pd.ExcelWriter('result_all.xlsx', engine='xlsxwriter') - for i in range(0,len(tables_all)): - table = tables_all[i].df - sheetname = str(i) - table.to_excel(result_all, sheetname,index=False) - with open('result_all.xlsx','rb') as f: - st.download_button('一件抽取完成,点击下载!', f,file_name='result_all.xlsx',mime="application/vnd.ms-excel") \ No newline at end of file diff --git a/spaces/bguberfain/Detic/detic/data/datasets/oid.py b/spaces/bguberfain/Detic/detic/data/datasets/oid.py deleted file mode 100644 index 90d7f8613e4f12e942ec8967db9f17c0ec0d41f4..0000000000000000000000000000000000000000 --- a/spaces/bguberfain/Detic/detic/data/datasets/oid.py +++ /dev/null @@ -1,535 +0,0 @@ -# Part of the code is from https://github.com/xingyizhou/UniDet/blob/master/projects/UniDet/unidet/data/datasets/oid.py -# Copyright (c) Facebook, Inc. and its affiliates. -from .register_oid import register_oid_instances -import os - -categories = [ - {'id': 1, 'name': 'Infant bed', 'freebase_id': '/m/061hd_'}, - {'id': 2, 'name': 'Rose', 'freebase_id': '/m/06m11'}, - {'id': 3, 'name': 'Flag', 'freebase_id': '/m/03120'}, - {'id': 4, 'name': 'Flashlight', 'freebase_id': '/m/01kb5b'}, - {'id': 5, 'name': 'Sea turtle', 'freebase_id': '/m/0120dh'}, - {'id': 6, 'name': 'Camera', 'freebase_id': '/m/0dv5r'}, - {'id': 7, 'name': 'Animal', 'freebase_id': '/m/0jbk'}, - {'id': 8, 'name': 'Glove', 'freebase_id': '/m/0174n1'}, - {'id': 9, 'name': 'Crocodile', 'freebase_id': '/m/09f_2'}, - {'id': 10, 'name': 'Cattle', 'freebase_id': '/m/01xq0k1'}, - {'id': 11, 'name': 'House', 'freebase_id': '/m/03jm5'}, - {'id': 12, 'name': 'Guacamole', 'freebase_id': '/m/02g30s'}, - {'id': 13, 'name': 'Penguin', 'freebase_id': '/m/05z6w'}, - {'id': 14, 'name': 'Vehicle registration plate', 'freebase_id': '/m/01jfm_'}, - {'id': 15, 'name': 'Bench', 'freebase_id': '/m/076lb9'}, - {'id': 16, 'name': 'Ladybug', 'freebase_id': '/m/0gj37'}, - {'id': 17, 'name': 'Human nose', 'freebase_id': '/m/0k0pj'}, - {'id': 18, 'name': 'Watermelon', 'freebase_id': '/m/0kpqd'}, - {'id': 19, 'name': 'Flute', 'freebase_id': '/m/0l14j_'}, - {'id': 20, 'name': 'Butterfly', 'freebase_id': '/m/0cyf8'}, - {'id': 21, 'name': 'Washing machine', 'freebase_id': '/m/0174k2'}, - {'id': 22, 'name': 'Raccoon', 'freebase_id': '/m/0dq75'}, - {'id': 23, 'name': 'Segway', 'freebase_id': '/m/076bq'}, - {'id': 24, 'name': 'Taco', 'freebase_id': '/m/07crc'}, - {'id': 25, 'name': 'Jellyfish', 'freebase_id': '/m/0d8zb'}, - {'id': 26, 'name': 'Cake', 'freebase_id': '/m/0fszt'}, - {'id': 27, 'name': 'Pen', 'freebase_id': '/m/0k1tl'}, - {'id': 28, 'name': 'Cannon', 'freebase_id': '/m/020kz'}, - {'id': 29, 'name': 'Bread', 'freebase_id': '/m/09728'}, - {'id': 30, 'name': 'Tree', 'freebase_id': '/m/07j7r'}, - {'id': 31, 'name': 'Shellfish', 'freebase_id': '/m/0fbdv'}, - {'id': 32, 'name': 'Bed', 'freebase_id': '/m/03ssj5'}, - {'id': 33, 'name': 'Hamster', 'freebase_id': '/m/03qrc'}, - {'id': 34, 'name': 'Hat', 'freebase_id': '/m/02dl1y'}, - {'id': 35, 'name': 'Toaster', 'freebase_id': '/m/01k6s3'}, - {'id': 36, 'name': 'Sombrero', 'freebase_id': '/m/02jfl0'}, - {'id': 37, 'name': 'Tiara', 'freebase_id': '/m/01krhy'}, - {'id': 38, 'name': 'Bowl', 'freebase_id': '/m/04kkgm'}, - {'id': 39, 'name': 'Dragonfly', 'freebase_id': '/m/0ft9s'}, - {'id': 40, 'name': 'Moths and butterflies', 'freebase_id': '/m/0d_2m'}, - {'id': 41, 'name': 'Antelope', 'freebase_id': '/m/0czz2'}, - {'id': 42, 'name': 'Vegetable', 'freebase_id': '/m/0f4s2w'}, - {'id': 43, 'name': 'Torch', 'freebase_id': '/m/07dd4'}, - {'id': 44, 'name': 'Building', 'freebase_id': '/m/0cgh4'}, - {'id': 45, 'name': 'Power plugs and sockets', 'freebase_id': '/m/03bbps'}, - {'id': 46, 'name': 'Blender', 'freebase_id': '/m/02pjr4'}, - {'id': 47, 'name': 'Billiard table', 'freebase_id': '/m/04p0qw'}, - {'id': 48, 'name': 'Cutting board', 'freebase_id': '/m/02pdsw'}, - {'id': 49, 'name': 'Bronze sculpture', 'freebase_id': '/m/01yx86'}, - {'id': 50, 'name': 'Turtle', 'freebase_id': '/m/09dzg'}, - {'id': 51, 'name': 'Broccoli', 'freebase_id': '/m/0hkxq'}, - {'id': 52, 'name': 'Tiger', 'freebase_id': '/m/07dm6'}, - {'id': 53, 'name': 'Mirror', 'freebase_id': '/m/054_l'}, - {'id': 54, 'name': 'Bear', 'freebase_id': '/m/01dws'}, - {'id': 55, 'name': 'Zucchini', 'freebase_id': '/m/027pcv'}, - {'id': 56, 'name': 'Dress', 'freebase_id': '/m/01d40f'}, - {'id': 57, 'name': 'Volleyball', 'freebase_id': '/m/02rgn06'}, - {'id': 58, 'name': 'Guitar', 'freebase_id': '/m/0342h'}, - {'id': 59, 'name': 'Reptile', 'freebase_id': '/m/06bt6'}, - {'id': 60, 'name': 'Golf cart', 'freebase_id': '/m/0323sq'}, - {'id': 61, 'name': 'Tart', 'freebase_id': '/m/02zvsm'}, - {'id': 62, 'name': 'Fedora', 'freebase_id': '/m/02fq_6'}, - {'id': 63, 'name': 'Carnivore', 'freebase_id': '/m/01lrl'}, - {'id': 64, 'name': 'Car', 'freebase_id': '/m/0k4j'}, - {'id': 65, 'name': 'Lighthouse', 'freebase_id': '/m/04h7h'}, - {'id': 66, 'name': 'Coffeemaker', 'freebase_id': '/m/07xyvk'}, - {'id': 67, 'name': 'Food processor', 'freebase_id': '/m/03y6mg'}, - {'id': 68, 'name': 'Truck', 'freebase_id': '/m/07r04'}, - {'id': 69, 'name': 'Bookcase', 'freebase_id': '/m/03__z0'}, - {'id': 70, 'name': 'Surfboard', 'freebase_id': '/m/019w40'}, - {'id': 71, 'name': 'Footwear', 'freebase_id': '/m/09j5n'}, - {'id': 72, 'name': 'Bench', 'freebase_id': '/m/0cvnqh'}, - {'id': 73, 'name': 'Necklace', 'freebase_id': '/m/01llwg'}, - {'id': 74, 'name': 'Flower', 'freebase_id': '/m/0c9ph5'}, - {'id': 75, 'name': 'Radish', 'freebase_id': '/m/015x5n'}, - {'id': 76, 'name': 'Marine mammal', 'freebase_id': '/m/0gd2v'}, - {'id': 77, 'name': 'Frying pan', 'freebase_id': '/m/04v6l4'}, - {'id': 78, 'name': 'Tap', 'freebase_id': '/m/02jz0l'}, - {'id': 79, 'name': 'Peach', 'freebase_id': '/m/0dj6p'}, - {'id': 80, 'name': 'Knife', 'freebase_id': '/m/04ctx'}, - {'id': 81, 'name': 'Handbag', 'freebase_id': '/m/080hkjn'}, - {'id': 82, 'name': 'Laptop', 'freebase_id': '/m/01c648'}, - {'id': 83, 'name': 'Tent', 'freebase_id': '/m/01j61q'}, - {'id': 84, 'name': 'Ambulance', 'freebase_id': '/m/012n7d'}, - {'id': 85, 'name': 'Christmas tree', 'freebase_id': '/m/025nd'}, - {'id': 86, 'name': 'Eagle', 'freebase_id': '/m/09csl'}, - {'id': 87, 'name': 'Limousine', 'freebase_id': '/m/01lcw4'}, - {'id': 88, 'name': 'Kitchen & dining room table', 'freebase_id': '/m/0h8n5zk'}, - {'id': 89, 'name': 'Polar bear', 'freebase_id': '/m/0633h'}, - {'id': 90, 'name': 'Tower', 'freebase_id': '/m/01fdzj'}, - {'id': 91, 'name': 'Football', 'freebase_id': '/m/01226z'}, - {'id': 92, 'name': 'Willow', 'freebase_id': '/m/0mw_6'}, - {'id': 93, 'name': 'Human head', 'freebase_id': '/m/04hgtk'}, - {'id': 94, 'name': 'Stop sign', 'freebase_id': '/m/02pv19'}, - {'id': 95, 'name': 'Banana', 'freebase_id': '/m/09qck'}, - {'id': 96, 'name': 'Mixer', 'freebase_id': '/m/063rgb'}, - {'id': 97, 'name': 'Binoculars', 'freebase_id': '/m/0lt4_'}, - {'id': 98, 'name': 'Dessert', 'freebase_id': '/m/0270h'}, - {'id': 99, 'name': 'Bee', 'freebase_id': '/m/01h3n'}, - {'id': 100, 'name': 'Chair', 'freebase_id': '/m/01mzpv'}, - {'id': 101, 'name': 'Wood-burning stove', 'freebase_id': '/m/04169hn'}, - {'id': 102, 'name': 'Flowerpot', 'freebase_id': '/m/0fm3zh'}, - {'id': 103, 'name': 'Beaker', 'freebase_id': '/m/0d20w4'}, - {'id': 104, 'name': 'Oyster', 'freebase_id': '/m/0_cp5'}, - {'id': 105, 'name': 'Woodpecker', 'freebase_id': '/m/01dy8n'}, - {'id': 106, 'name': 'Harp', 'freebase_id': '/m/03m5k'}, - {'id': 107, 'name': 'Bathtub', 'freebase_id': '/m/03dnzn'}, - {'id': 108, 'name': 'Wall clock', 'freebase_id': '/m/0h8mzrc'}, - {'id': 109, 'name': 'Sports uniform', 'freebase_id': '/m/0h8mhzd'}, - {'id': 110, 'name': 'Rhinoceros', 'freebase_id': '/m/03d443'}, - {'id': 111, 'name': 'Beehive', 'freebase_id': '/m/01gllr'}, - {'id': 112, 'name': 'Cupboard', 'freebase_id': '/m/0642b4'}, - {'id': 113, 'name': 'Chicken', 'freebase_id': '/m/09b5t'}, - {'id': 114, 'name': 'Man', 'freebase_id': '/m/04yx4'}, - {'id': 115, 'name': 'Blue jay', 'freebase_id': '/m/01f8m5'}, - {'id': 116, 'name': 'Cucumber', 'freebase_id': '/m/015x4r'}, - {'id': 117, 'name': 'Balloon', 'freebase_id': '/m/01j51'}, - {'id': 118, 'name': 'Kite', 'freebase_id': '/m/02zt3'}, - {'id': 119, 'name': 'Fireplace', 'freebase_id': '/m/03tw93'}, - {'id': 120, 'name': 'Lantern', 'freebase_id': '/m/01jfsr'}, - {'id': 121, 'name': 'Missile', 'freebase_id': '/m/04ylt'}, - {'id': 122, 'name': 'Book', 'freebase_id': '/m/0bt_c3'}, - {'id': 123, 'name': 'Spoon', 'freebase_id': '/m/0cmx8'}, - {'id': 124, 'name': 'Grapefruit', 'freebase_id': '/m/0hqkz'}, - {'id': 125, 'name': 'Squirrel', 'freebase_id': '/m/071qp'}, - {'id': 126, 'name': 'Orange', 'freebase_id': '/m/0cyhj_'}, - {'id': 127, 'name': 'Coat', 'freebase_id': '/m/01xygc'}, - {'id': 128, 'name': 'Punching bag', 'freebase_id': '/m/0420v5'}, - {'id': 129, 'name': 'Zebra', 'freebase_id': '/m/0898b'}, - {'id': 130, 'name': 'Billboard', 'freebase_id': '/m/01knjb'}, - {'id': 131, 'name': 'Bicycle', 'freebase_id': '/m/0199g'}, - {'id': 132, 'name': 'Door handle', 'freebase_id': '/m/03c7gz'}, - {'id': 133, 'name': 'Mechanical fan', 'freebase_id': '/m/02x984l'}, - {'id': 134, 'name': 'Ring binder', 'freebase_id': '/m/04zwwv'}, - {'id': 135, 'name': 'Table', 'freebase_id': '/m/04bcr3'}, - {'id': 136, 'name': 'Parrot', 'freebase_id': '/m/0gv1x'}, - {'id': 137, 'name': 'Sock', 'freebase_id': '/m/01nq26'}, - {'id': 138, 'name': 'Vase', 'freebase_id': '/m/02s195'}, - {'id': 139, 'name': 'Weapon', 'freebase_id': '/m/083kb'}, - {'id': 140, 'name': 'Shotgun', 'freebase_id': '/m/06nrc'}, - {'id': 141, 'name': 'Glasses', 'freebase_id': '/m/0jyfg'}, - {'id': 142, 'name': 'Seahorse', 'freebase_id': '/m/0nybt'}, - {'id': 143, 'name': 'Belt', 'freebase_id': '/m/0176mf'}, - {'id': 144, 'name': 'Watercraft', 'freebase_id': '/m/01rzcn'}, - {'id': 145, 'name': 'Window', 'freebase_id': '/m/0d4v4'}, - {'id': 146, 'name': 'Giraffe', 'freebase_id': '/m/03bk1'}, - {'id': 147, 'name': 'Lion', 'freebase_id': '/m/096mb'}, - {'id': 148, 'name': 'Tire', 'freebase_id': '/m/0h9mv'}, - {'id': 149, 'name': 'Vehicle', 'freebase_id': '/m/07yv9'}, - {'id': 150, 'name': 'Canoe', 'freebase_id': '/m/0ph39'}, - {'id': 151, 'name': 'Tie', 'freebase_id': '/m/01rkbr'}, - {'id': 152, 'name': 'Shelf', 'freebase_id': '/m/0gjbg72'}, - {'id': 153, 'name': 'Picture frame', 'freebase_id': '/m/06z37_'}, - {'id': 154, 'name': 'Printer', 'freebase_id': '/m/01m4t'}, - {'id': 155, 'name': 'Human leg', 'freebase_id': '/m/035r7c'}, - {'id': 156, 'name': 'Boat', 'freebase_id': '/m/019jd'}, - {'id': 157, 'name': 'Slow cooker', 'freebase_id': '/m/02tsc9'}, - {'id': 158, 'name': 'Croissant', 'freebase_id': '/m/015wgc'}, - {'id': 159, 'name': 'Candle', 'freebase_id': '/m/0c06p'}, - {'id': 160, 'name': 'Pancake', 'freebase_id': '/m/01dwwc'}, - {'id': 161, 'name': 'Pillow', 'freebase_id': '/m/034c16'}, - {'id': 162, 'name': 'Coin', 'freebase_id': '/m/0242l'}, - {'id': 163, 'name': 'Stretcher', 'freebase_id': '/m/02lbcq'}, - {'id': 164, 'name': 'Sandal', 'freebase_id': '/m/03nfch'}, - {'id': 165, 'name': 'Woman', 'freebase_id': '/m/03bt1vf'}, - {'id': 166, 'name': 'Stairs', 'freebase_id': '/m/01lynh'}, - {'id': 167, 'name': 'Harpsichord', 'freebase_id': '/m/03q5t'}, - {'id': 168, 'name': 'Stool', 'freebase_id': '/m/0fqt361'}, - {'id': 169, 'name': 'Bus', 'freebase_id': '/m/01bjv'}, - {'id': 170, 'name': 'Suitcase', 'freebase_id': '/m/01s55n'}, - {'id': 171, 'name': 'Human mouth', 'freebase_id': '/m/0283dt1'}, - {'id': 172, 'name': 'Juice', 'freebase_id': '/m/01z1kdw'}, - {'id': 173, 'name': 'Skull', 'freebase_id': '/m/016m2d'}, - {'id': 174, 'name': 'Door', 'freebase_id': '/m/02dgv'}, - {'id': 175, 'name': 'Violin', 'freebase_id': '/m/07y_7'}, - {'id': 176, 'name': 'Chopsticks', 'freebase_id': '/m/01_5g'}, - {'id': 177, 'name': 'Digital clock', 'freebase_id': '/m/06_72j'}, - {'id': 178, 'name': 'Sunflower', 'freebase_id': '/m/0ftb8'}, - {'id': 179, 'name': 'Leopard', 'freebase_id': '/m/0c29q'}, - {'id': 180, 'name': 'Bell pepper', 'freebase_id': '/m/0jg57'}, - {'id': 181, 'name': 'Harbor seal', 'freebase_id': '/m/02l8p9'}, - {'id': 182, 'name': 'Snake', 'freebase_id': '/m/078jl'}, - {'id': 183, 'name': 'Sewing machine', 'freebase_id': '/m/0llzx'}, - {'id': 184, 'name': 'Goose', 'freebase_id': '/m/0dbvp'}, - {'id': 185, 'name': 'Helicopter', 'freebase_id': '/m/09ct_'}, - {'id': 186, 'name': 'Seat belt', 'freebase_id': '/m/0dkzw'}, - {'id': 187, 'name': 'Coffee cup', 'freebase_id': '/m/02p5f1q'}, - {'id': 188, 'name': 'Microwave oven', 'freebase_id': '/m/0fx9l'}, - {'id': 189, 'name': 'Hot dog', 'freebase_id': '/m/01b9xk'}, - {'id': 190, 'name': 'Countertop', 'freebase_id': '/m/0b3fp9'}, - {'id': 191, 'name': 'Serving tray', 'freebase_id': '/m/0h8n27j'}, - {'id': 192, 'name': 'Dog bed', 'freebase_id': '/m/0h8n6f9'}, - {'id': 193, 'name': 'Beer', 'freebase_id': '/m/01599'}, - {'id': 194, 'name': 'Sunglasses', 'freebase_id': '/m/017ftj'}, - {'id': 195, 'name': 'Golf ball', 'freebase_id': '/m/044r5d'}, - {'id': 196, 'name': 'Waffle', 'freebase_id': '/m/01dwsz'}, - {'id': 197, 'name': 'Palm tree', 'freebase_id': '/m/0cdl1'}, - {'id': 198, 'name': 'Trumpet', 'freebase_id': '/m/07gql'}, - {'id': 199, 'name': 'Ruler', 'freebase_id': '/m/0hdln'}, - {'id': 200, 'name': 'Helmet', 'freebase_id': '/m/0zvk5'}, - {'id': 201, 'name': 'Ladder', 'freebase_id': '/m/012w5l'}, - {'id': 202, 'name': 'Office building', 'freebase_id': '/m/021sj1'}, - {'id': 203, 'name': 'Tablet computer', 'freebase_id': '/m/0bh9flk'}, - {'id': 204, 'name': 'Toilet paper', 'freebase_id': '/m/09gtd'}, - {'id': 205, 'name': 'Pomegranate', 'freebase_id': '/m/0jwn_'}, - {'id': 206, 'name': 'Skirt', 'freebase_id': '/m/02wv6h6'}, - {'id': 207, 'name': 'Gas stove', 'freebase_id': '/m/02wv84t'}, - {'id': 208, 'name': 'Cookie', 'freebase_id': '/m/021mn'}, - {'id': 209, 'name': 'Cart', 'freebase_id': '/m/018p4k'}, - {'id': 210, 'name': 'Raven', 'freebase_id': '/m/06j2d'}, - {'id': 211, 'name': 'Egg', 'freebase_id': '/m/033cnk'}, - {'id': 212, 'name': 'Burrito', 'freebase_id': '/m/01j3zr'}, - {'id': 213, 'name': 'Goat', 'freebase_id': '/m/03fwl'}, - {'id': 214, 'name': 'Kitchen knife', 'freebase_id': '/m/058qzx'}, - {'id': 215, 'name': 'Skateboard', 'freebase_id': '/m/06_fw'}, - {'id': 216, 'name': 'Salt and pepper shakers', 'freebase_id': '/m/02x8cch'}, - {'id': 217, 'name': 'Lynx', 'freebase_id': '/m/04g2r'}, - {'id': 218, 'name': 'Boot', 'freebase_id': '/m/01b638'}, - {'id': 219, 'name': 'Platter', 'freebase_id': '/m/099ssp'}, - {'id': 220, 'name': 'Ski', 'freebase_id': '/m/071p9'}, - {'id': 221, 'name': 'Swimwear', 'freebase_id': '/m/01gkx_'}, - {'id': 222, 'name': 'Swimming pool', 'freebase_id': '/m/0b_rs'}, - {'id': 223, 'name': 'Drinking straw', 'freebase_id': '/m/03v5tg'}, - {'id': 224, 'name': 'Wrench', 'freebase_id': '/m/01j5ks'}, - {'id': 225, 'name': 'Drum', 'freebase_id': '/m/026t6'}, - {'id': 226, 'name': 'Ant', 'freebase_id': '/m/0_k2'}, - {'id': 227, 'name': 'Human ear', 'freebase_id': '/m/039xj_'}, - {'id': 228, 'name': 'Headphones', 'freebase_id': '/m/01b7fy'}, - {'id': 229, 'name': 'Fountain', 'freebase_id': '/m/0220r2'}, - {'id': 230, 'name': 'Bird', 'freebase_id': '/m/015p6'}, - {'id': 231, 'name': 'Jeans', 'freebase_id': '/m/0fly7'}, - {'id': 232, 'name': 'Television', 'freebase_id': '/m/07c52'}, - {'id': 233, 'name': 'Crab', 'freebase_id': '/m/0n28_'}, - {'id': 234, 'name': 'Microphone', 'freebase_id': '/m/0hg7b'}, - {'id': 235, 'name': 'Home appliance', 'freebase_id': '/m/019dx1'}, - {'id': 236, 'name': 'Snowplow', 'freebase_id': '/m/04vv5k'}, - {'id': 237, 'name': 'Beetle', 'freebase_id': '/m/020jm'}, - {'id': 238, 'name': 'Artichoke', 'freebase_id': '/m/047v4b'}, - {'id': 239, 'name': 'Jet ski', 'freebase_id': '/m/01xs3r'}, - {'id': 240, 'name': 'Stationary bicycle', 'freebase_id': '/m/03kt2w'}, - {'id': 241, 'name': 'Human hair', 'freebase_id': '/m/03q69'}, - {'id': 242, 'name': 'Brown bear', 'freebase_id': '/m/01dxs'}, - {'id': 243, 'name': 'Starfish', 'freebase_id': '/m/01h8tj'}, - {'id': 244, 'name': 'Fork', 'freebase_id': '/m/0dt3t'}, - {'id': 245, 'name': 'Lobster', 'freebase_id': '/m/0cjq5'}, - {'id': 246, 'name': 'Corded phone', 'freebase_id': '/m/0h8lkj8'}, - {'id': 247, 'name': 'Drink', 'freebase_id': '/m/0271t'}, - {'id': 248, 'name': 'Saucer', 'freebase_id': '/m/03q5c7'}, - {'id': 249, 'name': 'Carrot', 'freebase_id': '/m/0fj52s'}, - {'id': 250, 'name': 'Insect', 'freebase_id': '/m/03vt0'}, - {'id': 251, 'name': 'Clock', 'freebase_id': '/m/01x3z'}, - {'id': 252, 'name': 'Castle', 'freebase_id': '/m/0d5gx'}, - {'id': 253, 'name': 'Tennis racket', 'freebase_id': '/m/0h8my_4'}, - {'id': 254, 'name': 'Ceiling fan', 'freebase_id': '/m/03ldnb'}, - {'id': 255, 'name': 'Asparagus', 'freebase_id': '/m/0cjs7'}, - {'id': 256, 'name': 'Jaguar', 'freebase_id': '/m/0449p'}, - {'id': 257, 'name': 'Musical instrument', 'freebase_id': '/m/04szw'}, - {'id': 258, 'name': 'Train', 'freebase_id': '/m/07jdr'}, - {'id': 259, 'name': 'Cat', 'freebase_id': '/m/01yrx'}, - {'id': 260, 'name': 'Rifle', 'freebase_id': '/m/06c54'}, - {'id': 261, 'name': 'Dumbbell', 'freebase_id': '/m/04h8sr'}, - {'id': 262, 'name': 'Mobile phone', 'freebase_id': '/m/050k8'}, - {'id': 263, 'name': 'Taxi', 'freebase_id': '/m/0pg52'}, - {'id': 264, 'name': 'Shower', 'freebase_id': '/m/02f9f_'}, - {'id': 265, 'name': 'Pitcher', 'freebase_id': '/m/054fyh'}, - {'id': 266, 'name': 'Lemon', 'freebase_id': '/m/09k_b'}, - {'id': 267, 'name': 'Invertebrate', 'freebase_id': '/m/03xxp'}, - {'id': 268, 'name': 'Turkey', 'freebase_id': '/m/0jly1'}, - {'id': 269, 'name': 'High heels', 'freebase_id': '/m/06k2mb'}, - {'id': 270, 'name': 'Bust', 'freebase_id': '/m/04yqq2'}, - {'id': 271, 'name': 'Elephant', 'freebase_id': '/m/0bwd_0j'}, - {'id': 272, 'name': 'Scarf', 'freebase_id': '/m/02h19r'}, - {'id': 273, 'name': 'Barrel', 'freebase_id': '/m/02zn6n'}, - {'id': 274, 'name': 'Trombone', 'freebase_id': '/m/07c6l'}, - {'id': 275, 'name': 'Pumpkin', 'freebase_id': '/m/05zsy'}, - {'id': 276, 'name': 'Box', 'freebase_id': '/m/025dyy'}, - {'id': 277, 'name': 'Tomato', 'freebase_id': '/m/07j87'}, - {'id': 278, 'name': 'Frog', 'freebase_id': '/m/09ld4'}, - {'id': 279, 'name': 'Bidet', 'freebase_id': '/m/01vbnl'}, - {'id': 280, 'name': 'Human face', 'freebase_id': '/m/0dzct'}, - {'id': 281, 'name': 'Houseplant', 'freebase_id': '/m/03fp41'}, - {'id': 282, 'name': 'Van', 'freebase_id': '/m/0h2r6'}, - {'id': 283, 'name': 'Shark', 'freebase_id': '/m/0by6g'}, - {'id': 284, 'name': 'Ice cream', 'freebase_id': '/m/0cxn2'}, - {'id': 285, 'name': 'Swim cap', 'freebase_id': '/m/04tn4x'}, - {'id': 286, 'name': 'Falcon', 'freebase_id': '/m/0f6wt'}, - {'id': 287, 'name': 'Ostrich', 'freebase_id': '/m/05n4y'}, - {'id': 288, 'name': 'Handgun', 'freebase_id': '/m/0gxl3'}, - {'id': 289, 'name': 'Whiteboard', 'freebase_id': '/m/02d9qx'}, - {'id': 290, 'name': 'Lizard', 'freebase_id': '/m/04m9y'}, - {'id': 291, 'name': 'Pasta', 'freebase_id': '/m/05z55'}, - {'id': 292, 'name': 'Snowmobile', 'freebase_id': '/m/01x3jk'}, - {'id': 293, 'name': 'Light bulb', 'freebase_id': '/m/0h8l4fh'}, - {'id': 294, 'name': 'Window blind', 'freebase_id': '/m/031b6r'}, - {'id': 295, 'name': 'Muffin', 'freebase_id': '/m/01tcjp'}, - {'id': 296, 'name': 'Pretzel', 'freebase_id': '/m/01f91_'}, - {'id': 297, 'name': 'Computer monitor', 'freebase_id': '/m/02522'}, - {'id': 298, 'name': 'Horn', 'freebase_id': '/m/0319l'}, - {'id': 299, 'name': 'Furniture', 'freebase_id': '/m/0c_jw'}, - {'id': 300, 'name': 'Sandwich', 'freebase_id': '/m/0l515'}, - {'id': 301, 'name': 'Fox', 'freebase_id': '/m/0306r'}, - {'id': 302, 'name': 'Convenience store', 'freebase_id': '/m/0crjs'}, - {'id': 303, 'name': 'Fish', 'freebase_id': '/m/0ch_cf'}, - {'id': 304, 'name': 'Fruit', 'freebase_id': '/m/02xwb'}, - {'id': 305, 'name': 'Earrings', 'freebase_id': '/m/01r546'}, - {'id': 306, 'name': 'Curtain', 'freebase_id': '/m/03rszm'}, - {'id': 307, 'name': 'Grape', 'freebase_id': '/m/0388q'}, - {'id': 308, 'name': 'Sofa bed', 'freebase_id': '/m/03m3pdh'}, - {'id': 309, 'name': 'Horse', 'freebase_id': '/m/03k3r'}, - {'id': 310, 'name': 'Luggage and bags', 'freebase_id': '/m/0hf58v5'}, - {'id': 311, 'name': 'Desk', 'freebase_id': '/m/01y9k5'}, - {'id': 312, 'name': 'Crutch', 'freebase_id': '/m/05441v'}, - {'id': 313, 'name': 'Bicycle helmet', 'freebase_id': '/m/03p3bw'}, - {'id': 314, 'name': 'Tick', 'freebase_id': '/m/0175cv'}, - {'id': 315, 'name': 'Airplane', 'freebase_id': '/m/0cmf2'}, - {'id': 316, 'name': 'Canary', 'freebase_id': '/m/0ccs93'}, - {'id': 317, 'name': 'Spatula', 'freebase_id': '/m/02d1br'}, - {'id': 318, 'name': 'Watch', 'freebase_id': '/m/0gjkl'}, - {'id': 319, 'name': 'Lily', 'freebase_id': '/m/0jqgx'}, - {'id': 320, 'name': 'Kitchen appliance', 'freebase_id': '/m/0h99cwc'}, - {'id': 321, 'name': 'Filing cabinet', 'freebase_id': '/m/047j0r'}, - {'id': 322, 'name': 'Aircraft', 'freebase_id': '/m/0k5j'}, - {'id': 323, 'name': 'Cake stand', 'freebase_id': '/m/0h8n6ft'}, - {'id': 324, 'name': 'Candy', 'freebase_id': '/m/0gm28'}, - {'id': 325, 'name': 'Sink', 'freebase_id': '/m/0130jx'}, - {'id': 326, 'name': 'Mouse', 'freebase_id': '/m/04rmv'}, - {'id': 327, 'name': 'Wine', 'freebase_id': '/m/081qc'}, - {'id': 328, 'name': 'Wheelchair', 'freebase_id': '/m/0qmmr'}, - {'id': 329, 'name': 'Goldfish', 'freebase_id': '/m/03fj2'}, - {'id': 330, 'name': 'Refrigerator', 'freebase_id': '/m/040b_t'}, - {'id': 331, 'name': 'French fries', 'freebase_id': '/m/02y6n'}, - {'id': 332, 'name': 'Drawer', 'freebase_id': '/m/0fqfqc'}, - {'id': 333, 'name': 'Treadmill', 'freebase_id': '/m/030610'}, - {'id': 334, 'name': 'Picnic basket', 'freebase_id': '/m/07kng9'}, - {'id': 335, 'name': 'Dice', 'freebase_id': '/m/029b3'}, - {'id': 336, 'name': 'Cabbage', 'freebase_id': '/m/0fbw6'}, - {'id': 337, 'name': 'Football helmet', 'freebase_id': '/m/07qxg_'}, - {'id': 338, 'name': 'Pig', 'freebase_id': '/m/068zj'}, - {'id': 339, 'name': 'Person', 'freebase_id': '/m/01g317'}, - {'id': 340, 'name': 'Shorts', 'freebase_id': '/m/01bfm9'}, - {'id': 341, 'name': 'Gondola', 'freebase_id': '/m/02068x'}, - {'id': 342, 'name': 'Honeycomb', 'freebase_id': '/m/0fz0h'}, - {'id': 343, 'name': 'Doughnut', 'freebase_id': '/m/0jy4k'}, - {'id': 344, 'name': 'Chest of drawers', 'freebase_id': '/m/05kyg_'}, - {'id': 345, 'name': 'Land vehicle', 'freebase_id': '/m/01prls'}, - {'id': 346, 'name': 'Bat', 'freebase_id': '/m/01h44'}, - {'id': 347, 'name': 'Monkey', 'freebase_id': '/m/08pbxl'}, - {'id': 348, 'name': 'Dagger', 'freebase_id': '/m/02gzp'}, - {'id': 349, 'name': 'Tableware', 'freebase_id': '/m/04brg2'}, - {'id': 350, 'name': 'Human foot', 'freebase_id': '/m/031n1'}, - {'id': 351, 'name': 'Mug', 'freebase_id': '/m/02jvh9'}, - {'id': 352, 'name': 'Alarm clock', 'freebase_id': '/m/046dlr'}, - {'id': 353, 'name': 'Pressure cooker', 'freebase_id': '/m/0h8ntjv'}, - {'id': 354, 'name': 'Human hand', 'freebase_id': '/m/0k65p'}, - {'id': 355, 'name': 'Tortoise', 'freebase_id': '/m/011k07'}, - {'id': 356, 'name': 'Baseball glove', 'freebase_id': '/m/03grzl'}, - {'id': 357, 'name': 'Sword', 'freebase_id': '/m/06y5r'}, - {'id': 358, 'name': 'Pear', 'freebase_id': '/m/061_f'}, - {'id': 359, 'name': 'Miniskirt', 'freebase_id': '/m/01cmb2'}, - {'id': 360, 'name': 'Traffic sign', 'freebase_id': '/m/01mqdt'}, - {'id': 361, 'name': 'Girl', 'freebase_id': '/m/05r655'}, - {'id': 362, 'name': 'Roller skates', 'freebase_id': '/m/02p3w7d'}, - {'id': 363, 'name': 'Dinosaur', 'freebase_id': '/m/029tx'}, - {'id': 364, 'name': 'Porch', 'freebase_id': '/m/04m6gz'}, - {'id': 365, 'name': 'Human beard', 'freebase_id': '/m/015h_t'}, - {'id': 366, 'name': 'Submarine sandwich', 'freebase_id': '/m/06pcq'}, - {'id': 367, 'name': 'Screwdriver', 'freebase_id': '/m/01bms0'}, - {'id': 368, 'name': 'Strawberry', 'freebase_id': '/m/07fbm7'}, - {'id': 369, 'name': 'Wine glass', 'freebase_id': '/m/09tvcd'}, - {'id': 370, 'name': 'Seafood', 'freebase_id': '/m/06nwz'}, - {'id': 371, 'name': 'Racket', 'freebase_id': '/m/0dv9c'}, - {'id': 372, 'name': 'Wheel', 'freebase_id': '/m/083wq'}, - {'id': 373, 'name': 'Sea lion', 'freebase_id': '/m/0gd36'}, - {'id': 374, 'name': 'Toy', 'freebase_id': '/m/0138tl'}, - {'id': 375, 'name': 'Tea', 'freebase_id': '/m/07clx'}, - {'id': 376, 'name': 'Tennis ball', 'freebase_id': '/m/05ctyq'}, - {'id': 377, 'name': 'Waste container', 'freebase_id': '/m/0bjyj5'}, - {'id': 378, 'name': 'Mule', 'freebase_id': '/m/0dbzx'}, - {'id': 379, 'name': 'Cricket ball', 'freebase_id': '/m/02ctlc'}, - {'id': 380, 'name': 'Pineapple', 'freebase_id': '/m/0fp6w'}, - {'id': 381, 'name': 'Coconut', 'freebase_id': '/m/0djtd'}, - {'id': 382, 'name': 'Doll', 'freebase_id': '/m/0167gd'}, - {'id': 383, 'name': 'Coffee table', 'freebase_id': '/m/078n6m'}, - {'id': 384, 'name': 'Snowman', 'freebase_id': '/m/0152hh'}, - {'id': 385, 'name': 'Lavender', 'freebase_id': '/m/04gth'}, - {'id': 386, 'name': 'Shrimp', 'freebase_id': '/m/0ll1f78'}, - {'id': 387, 'name': 'Maple', 'freebase_id': '/m/0cffdh'}, - {'id': 388, 'name': 'Cowboy hat', 'freebase_id': '/m/025rp__'}, - {'id': 389, 'name': 'Goggles', 'freebase_id': '/m/02_n6y'}, - {'id': 390, 'name': 'Rugby ball', 'freebase_id': '/m/0wdt60w'}, - {'id': 391, 'name': 'Caterpillar', 'freebase_id': '/m/0cydv'}, - {'id': 392, 'name': 'Poster', 'freebase_id': '/m/01n5jq'}, - {'id': 393, 'name': 'Rocket', 'freebase_id': '/m/09rvcxw'}, - {'id': 394, 'name': 'Organ', 'freebase_id': '/m/013y1f'}, - {'id': 395, 'name': 'Saxophone', 'freebase_id': '/m/06ncr'}, - {'id': 396, 'name': 'Traffic light', 'freebase_id': '/m/015qff'}, - {'id': 397, 'name': 'Cocktail', 'freebase_id': '/m/024g6'}, - {'id': 398, 'name': 'Plastic bag', 'freebase_id': '/m/05gqfk'}, - {'id': 399, 'name': 'Squash', 'freebase_id': '/m/0dv77'}, - {'id': 400, 'name': 'Mushroom', 'freebase_id': '/m/052sf'}, - {'id': 401, 'name': 'Hamburger', 'freebase_id': '/m/0cdn1'}, - {'id': 402, 'name': 'Light switch', 'freebase_id': '/m/03jbxj'}, - {'id': 403, 'name': 'Parachute', 'freebase_id': '/m/0cyfs'}, - {'id': 404, 'name': 'Teddy bear', 'freebase_id': '/m/0kmg4'}, - {'id': 405, 'name': 'Winter melon', 'freebase_id': '/m/02cvgx'}, - {'id': 406, 'name': 'Deer', 'freebase_id': '/m/09kx5'}, - {'id': 407, 'name': 'Musical keyboard', 'freebase_id': '/m/057cc'}, - {'id': 408, 'name': 'Plumbing fixture', 'freebase_id': '/m/02pkr5'}, - {'id': 409, 'name': 'Scoreboard', 'freebase_id': '/m/057p5t'}, - {'id': 410, 'name': 'Baseball bat', 'freebase_id': '/m/03g8mr'}, - {'id': 411, 'name': 'Envelope', 'freebase_id': '/m/0frqm'}, - {'id': 412, 'name': 'Adhesive tape', 'freebase_id': '/m/03m3vtv'}, - {'id': 413, 'name': 'Briefcase', 'freebase_id': '/m/0584n8'}, - {'id': 414, 'name': 'Paddle', 'freebase_id': '/m/014y4n'}, - {'id': 415, 'name': 'Bow and arrow', 'freebase_id': '/m/01g3x7'}, - {'id': 416, 'name': 'Telephone', 'freebase_id': '/m/07cx4'}, - {'id': 417, 'name': 'Sheep', 'freebase_id': '/m/07bgp'}, - {'id': 418, 'name': 'Jacket', 'freebase_id': '/m/032b3c'}, - {'id': 419, 'name': 'Boy', 'freebase_id': '/m/01bl7v'}, - {'id': 420, 'name': 'Pizza', 'freebase_id': '/m/0663v'}, - {'id': 421, 'name': 'Otter', 'freebase_id': '/m/0cn6p'}, - {'id': 422, 'name': 'Office supplies', 'freebase_id': '/m/02rdsp'}, - {'id': 423, 'name': 'Couch', 'freebase_id': '/m/02crq1'}, - {'id': 424, 'name': 'Cello', 'freebase_id': '/m/01xqw'}, - {'id': 425, 'name': 'Bull', 'freebase_id': '/m/0cnyhnx'}, - {'id': 426, 'name': 'Camel', 'freebase_id': '/m/01x_v'}, - {'id': 427, 'name': 'Ball', 'freebase_id': '/m/018xm'}, - {'id': 428, 'name': 'Duck', 'freebase_id': '/m/09ddx'}, - {'id': 429, 'name': 'Whale', 'freebase_id': '/m/084zz'}, - {'id': 430, 'name': 'Shirt', 'freebase_id': '/m/01n4qj'}, - {'id': 431, 'name': 'Tank', 'freebase_id': '/m/07cmd'}, - {'id': 432, 'name': 'Motorcycle', 'freebase_id': '/m/04_sv'}, - {'id': 433, 'name': 'Accordion', 'freebase_id': '/m/0mkg'}, - {'id': 434, 'name': 'Owl', 'freebase_id': '/m/09d5_'}, - {'id': 435, 'name': 'Porcupine', 'freebase_id': '/m/0c568'}, - {'id': 436, 'name': 'Sun hat', 'freebase_id': '/m/02wbtzl'}, - {'id': 437, 'name': 'Nail', 'freebase_id': '/m/05bm6'}, - {'id': 438, 'name': 'Scissors', 'freebase_id': '/m/01lsmm'}, - {'id': 439, 'name': 'Swan', 'freebase_id': '/m/0dftk'}, - {'id': 440, 'name': 'Lamp', 'freebase_id': '/m/0dtln'}, - {'id': 441, 'name': 'Crown', 'freebase_id': '/m/0nl46'}, - {'id': 442, 'name': 'Piano', 'freebase_id': '/m/05r5c'}, - {'id': 443, 'name': 'Sculpture', 'freebase_id': '/m/06msq'}, - {'id': 444, 'name': 'Cheetah', 'freebase_id': '/m/0cd4d'}, - {'id': 445, 'name': 'Oboe', 'freebase_id': '/m/05kms'}, - {'id': 446, 'name': 'Tin can', 'freebase_id': '/m/02jnhm'}, - {'id': 447, 'name': 'Mango', 'freebase_id': '/m/0fldg'}, - {'id': 448, 'name': 'Tripod', 'freebase_id': '/m/073bxn'}, - {'id': 449, 'name': 'Oven', 'freebase_id': '/m/029bxz'}, - {'id': 450, 'name': 'Mouse', 'freebase_id': '/m/020lf'}, - {'id': 451, 'name': 'Barge', 'freebase_id': '/m/01btn'}, - {'id': 452, 'name': 'Coffee', 'freebase_id': '/m/02vqfm'}, - {'id': 453, 'name': 'Snowboard', 'freebase_id': '/m/06__v'}, - {'id': 454, 'name': 'Common fig', 'freebase_id': '/m/043nyj'}, - {'id': 455, 'name': 'Salad', 'freebase_id': '/m/0grw1'}, - {'id': 456, 'name': 'Marine invertebrates', 'freebase_id': '/m/03hl4l9'}, - {'id': 457, 'name': 'Umbrella', 'freebase_id': '/m/0hnnb'}, - {'id': 458, 'name': 'Kangaroo', 'freebase_id': '/m/04c0y'}, - {'id': 459, 'name': 'Human arm', 'freebase_id': '/m/0dzf4'}, - {'id': 460, 'name': 'Measuring cup', 'freebase_id': '/m/07v9_z'}, - {'id': 461, 'name': 'Snail', 'freebase_id': '/m/0f9_l'}, - {'id': 462, 'name': 'Loveseat', 'freebase_id': '/m/0703r8'}, - {'id': 463, 'name': 'Suit', 'freebase_id': '/m/01xyhv'}, - {'id': 464, 'name': 'Teapot', 'freebase_id': '/m/01fh4r'}, - {'id': 465, 'name': 'Bottle', 'freebase_id': '/m/04dr76w'}, - {'id': 466, 'name': 'Alpaca', 'freebase_id': '/m/0pcr'}, - {'id': 467, 'name': 'Kettle', 'freebase_id': '/m/03s_tn'}, - {'id': 468, 'name': 'Trousers', 'freebase_id': '/m/07mhn'}, - {'id': 469, 'name': 'Popcorn', 'freebase_id': '/m/01hrv5'}, - {'id': 470, 'name': 'Centipede', 'freebase_id': '/m/019h78'}, - {'id': 471, 'name': 'Spider', 'freebase_id': '/m/09kmb'}, - {'id': 472, 'name': 'Sparrow', 'freebase_id': '/m/0h23m'}, - {'id': 473, 'name': 'Plate', 'freebase_id': '/m/050gv4'}, - {'id': 474, 'name': 'Bagel', 'freebase_id': '/m/01fb_0'}, - {'id': 475, 'name': 'Personal care', 'freebase_id': '/m/02w3_ws'}, - {'id': 476, 'name': 'Apple', 'freebase_id': '/m/014j1m'}, - {'id': 477, 'name': 'Brassiere', 'freebase_id': '/m/01gmv2'}, - {'id': 478, 'name': 'Bathroom cabinet', 'freebase_id': '/m/04y4h8h'}, - {'id': 479, 'name': 'studio couch', 'freebase_id': '/m/026qbn5'}, - {'id': 480, 'name': 'Computer keyboard', 'freebase_id': '/m/01m2v'}, - {'id': 481, 'name': 'Table tennis racket', 'freebase_id': '/m/05_5p_0'}, - {'id': 482, 'name': 'Sushi', 'freebase_id': '/m/07030'}, - {'id': 483, 'name': 'Cabinetry', 'freebase_id': '/m/01s105'}, - {'id': 484, 'name': 'Street light', 'freebase_id': '/m/033rq4'}, - {'id': 485, 'name': 'Towel', 'freebase_id': '/m/0162_1'}, - {'id': 486, 'name': 'Nightstand', 'freebase_id': '/m/02z51p'}, - {'id': 487, 'name': 'Rabbit', 'freebase_id': '/m/06mf6'}, - {'id': 488, 'name': 'Dolphin', 'freebase_id': '/m/02hj4'}, - {'id': 489, 'name': 'Dog', 'freebase_id': '/m/0bt9lr'}, - {'id': 490, 'name': 'Jug', 'freebase_id': '/m/08hvt4'}, - {'id': 491, 'name': 'Wok', 'freebase_id': '/m/084rd'}, - {'id': 492, 'name': 'Fire hydrant', 'freebase_id': '/m/01pns0'}, - {'id': 493, 'name': 'Human eye', 'freebase_id': '/m/014sv8'}, - {'id': 494, 'name': 'Skyscraper', 'freebase_id': '/m/079cl'}, - {'id': 495, 'name': 'Backpack', 'freebase_id': '/m/01940j'}, - {'id': 496, 'name': 'Potato', 'freebase_id': '/m/05vtc'}, - {'id': 497, 'name': 'Paper towel', 'freebase_id': '/m/02w3r3'}, - {'id': 498, 'name': 'Lifejacket', 'freebase_id': '/m/054xkw'}, - {'id': 499, 'name': 'Bicycle wheel', 'freebase_id': '/m/01bqk0'}, - {'id': 500, 'name': 'Toilet', 'freebase_id': '/m/09g1w'}, -] - - -def _get_builtin_metadata(cats): - id_to_name = {x['id']: x['name'] for x in cats} - thing_dataset_id_to_contiguous_id = {i + 1: i for i in range(len(cats))} - thing_classes = [x['name'] for x in sorted(cats, key=lambda x: x['id'])] - return { - "thing_dataset_id_to_contiguous_id": thing_dataset_id_to_contiguous_id, - "thing_classes": thing_classes} - -_PREDEFINED_SPLITS_OID = { - # cat threshold: 500, 1500: r 170, c 151, f 179 - "oid_train": ("oid/images/", "oid/annotations/oid_challenge_2019_train_bbox.json"), - # "expanded" duplicates annotations to their father classes based on the official - # hierarchy. This is used in the official evaulation protocol. - # https://storage.googleapis.com/openimages/web/evaluation.html - "oid_val_expanded": ("oid/images/validation/", "oid/annotations/oid_challenge_2019_val_expanded.json"), - "oid_val_expanded_rare": ("oid/images/validation/", "oid/annotations/oid_challenge_2019_val_expanded_rare.json"), -} - - -for key, (image_root, json_file) in _PREDEFINED_SPLITS_OID.items(): - register_oid_instances( - key, - _get_builtin_metadata(categories), - os.path.join("datasets", json_file) if "://" not in json_file else json_file, - os.path.join("datasets", image_root), - ) \ No newline at end of file diff --git a/spaces/bigscience/petals-api/src/bloom/ops.py b/spaces/bigscience/petals-api/src/bloom/ops.py deleted file mode 100644 index 0ef9b5edfd2cceb6faac0e527248b6f96046e221..0000000000000000000000000000000000000000 --- a/spaces/bigscience/petals-api/src/bloom/ops.py +++ /dev/null @@ -1,246 +0,0 @@ -""" -Utility operations used in the the BLOOM model -Based on https://github.com/huggingface/transformers/commit/ca2a55e9dfb245527b5e1c954fec6ffbb7aef07b -See commit history for authorship. -""" -import math - -import torch -import torch.autograd -import torch.nn.functional as F -from torch import nn - - -def split_tensor_along_last_dim(tensor, num_partitions, contiguous_split_chunks=False): - """Split a tensor along its last dimension. - - Args: - tensor: ([`torch.tensor`], *required*): - input tensor to split - num_partitions ([`int`], *required*): - number of partitions to split the tensor - contiguous_split_chunks ([`bool`], *optional*, default=`False`):: - If True, make each chunk contiguous in memory. - """ - # Get the size and dimension. - last_dim = tensor.dim() - 1 - numerator, denominator = tensor.size()[last_dim], num_partitions - if not (numerator % denominator == 0): - raise ValueError(f"{numerator} is not divisible by {denominator}") - last_dim_size = numerator // denominator - # Split. - tensor_list = torch.split(tensor, last_dim_size, dim=last_dim) - # Note: torch.split does not create contiguous tensors by default. - if contiguous_split_chunks: - return tuple(chunk.contiguous() for chunk in tensor_list) - - return tensor_list - - -def attention_mask_func(attention_scores, attention_mask, causal_mask): - if attention_mask.dtype == torch.bool: - attention_mask_bool = ~attention_mask - else: - attention_mask_bool = (1 - attention_mask).bool() - - query_length, key_length, n_heads = attention_scores.size(2), attention_scores.size(3), attention_scores.size(1) - padded_causal_mask = ( - attention_mask_bool[:, None, key_length - query_length : key_length, None] - + ~causal_mask[:, :, key_length - query_length : key_length, :key_length] - ).bool() - padded_causal_mask = padded_causal_mask + attention_mask_bool[:, None, None, :key_length].bool() - # Make use of floats - return ( - attention_scores.masked_fill_(padded_causal_mask.expand(-1, n_heads, -1, -1), -10000.0), - padded_causal_mask, - ) - - -def build_alibi_tensor( - max_seq_len: int, n_head: int, dtype: torch.dtype = torch.bfloat16, device: torch.device = torch.device("cpu") -) -> torch.Tensor: - """ - Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it - relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value - `softmax(l+a) = softmax(l)`. Based on - https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742 - Args: - Returns tensor shaped (n_head, 1, max_seq_len) - max_seq_len: (`int`, *required*): - max sequence length - n_head: (`int`, *required*): - number of heads - dtype: (`torch.dtype`, *optional*, default=`torch.bfloat16`): - dtype of the output tensor - device: (`torch.device`, *optional*, default=`torch.device('cpu')`): - device of the output alibi tensor - """ - closest_power_of_2 = 2 ** math.floor(math.log2(n_head)) - base = torch.tensor(2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32) - powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32) - slopes = torch.pow(base, powers) - - if closest_power_of_2 != n_head: - extra_base = torch.tensor( - 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32 - ) - num_remaining_heads = min(closest_power_of_2, n_head - closest_power_of_2) - extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32) - slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0) - - lengths = torch.arange(max_seq_len, device=device, dtype=torch.int32) - return (slopes.view(-1, 1, 1) * lengths.view(1, 1, -1)).to(dtype) - - -def pre_process_alibi_for_pad(alibi: torch.Tensor, attention_mask: torch.Tensor): - """ - Args: - Pre-process the alibi tensor for padding. - alibi: ([`torch.tensor`], *required*): - alibi tensor to pre-process - attention_mask: ([`torch.tensor`], *required*): - attention mask to pre-process - """ - assert attention_mask.shape.ndim == 2, "mask should be [batch_size, seq_length]" - unpadded_indices = torch.relu(attention_mask.cumsum(dim=1) - 1) - # ^-- [batch, max_len], values correspond to element indices after removing padding - # We shift the alibi tensor + replace all the values where attention_mask==0.0 by 0 - alibi = alibi.take_along_dim(unpadded_indices.unsqueeze(0), -1) * attention_mask.unsqueeze(0) - return alibi.reshape(alibi.shape[0] * alibi.shape[1], 1, -1) - - -def dropout_add(x, residual, prob, training): - """ - Dropout add function - - Args: - x (`torch.tensor`, *required*): - input tensor - residual (`torch.tensor`, *rquired*): - esidual tensor - prob (`float`, *required*): - dropout probability - training (`bool`, *required*): - training mode - """ - out = nn.functional.dropout(x, p=prob, training=training) - out = residual + out - return out - - -def bloom_gelu_forward(x): - """ - Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to - make the model jitable. - - Args: - x (`torch.tensor`, *required*): - input hidden states - """ - return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))) - - -def bloom_gelu_back(g, x): - """ - gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) + - 0.3989423 * x * torch.exp(-0.5 * x * x) - - Args: - g (`torch.tensor`, *required*): - gradient output tensor - x (`torch.tensor`, *required*): - input tensor - """ - x = x[0] # x is a tuple of 1 element, needs to unpack it first - tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)) - # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243 - ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out) - return ff * g - - -class GeLUFunction(torch.autograd.Function): - @staticmethod - def forward(ctx, input): - ctx.save_for_backward(input) - return bloom_gelu_forward(input) - - @staticmethod - def backward(ctx, grad_output): - input = ctx.saved_tensors - tmp = bloom_gelu_back(grad_output, input) - return tmp - - -class BloomGelu(nn.Module): - """ - BloomBiasGelu wrapper function that make use of the simple function on inference mode to make the model - torchscriptable and use the autograd function in training mode to get the accurate results of the gradients Partly - copied from Megatron-DeepSpeed code and adapted for our needs - - See here why autograd functions are not torchscriptable: https://github.com/pytorch/pytorch/issues/22329 - - """ - - def __init__(self): - super().__init__() - - def forward(self, x): - if self.training: - return GeLUFunction.apply(x) - else: - return bloom_gelu_forward(x) - - -class BloomScaledSoftmax(nn.Module): - """ - fused operation: scaling + mask + softmax - - Args: - input_in_fp16 (`bool`, *required*): - flag to indicate if input in fp16 data format. - input_in_bf16 (`bool`, *required*): - flag to indicate if input in bf16 data format. - scaled_masked_softmax_fusion (`bool`, *required*): - flag to indicate user want to use softmax fusion - mask_func (`function`, *required*): - mask function to be applied. - softmax_in_fp32 (`bool`, *required*): - if true, softmax in performed at fp32 precision. - scale (`float`, *required*): - scaling factor used in input tensor scaling. - """ - - def __init__(self, scaled_masked_softmax_fusion, mask_func, softmax_in_fp32, scale): - super().__init__() - self.scaled_masked_softmax_fusion = scaled_masked_softmax_fusion - self.mask_func = mask_func - self.softmax_in_fp32 = softmax_in_fp32 - self.scale = scale - - if not (self.scale is None or softmax_in_fp32): - raise ValueError("softmax should be in fp32 when scaled") - - def forward(self, input, mask, max_positions): - input_dtype = input.dtype - input_in_16bit = input_dtype in [torch.float16, torch.bfloat16] - softmax_dtype = torch.float32 if self.softmax_in_fp32 else input_dtype - - if self.scale is not None: - input = input * self.scale - - if mask is None: - mask = torch.ones(input.shape[0], max_positions, dtype=torch.bool, device=input.device) - - mask = mask.to(input.device) - causal_mask = ( - torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)) - .view(1, 1, max_positions, max_positions) - .to(input.device) - ) - mask_output, padded_causal_mask = self.mask_func(input, mask, causal_mask) - probs = F.softmax(mask_output, dim=-1, dtype=softmax_dtype) * (~padded_causal_mask) - - if input_in_16bit and self.softmax_in_fp32: - probs = probs.to(dtype=input_dtype) - - return probs diff --git a/spaces/bioriAsaeru/text-to-voice/Avant-garde Rock Collection [Part 4] The Best Experimental Rock Albums of All Time.md b/spaces/bioriAsaeru/text-to-voice/Avant-garde Rock Collection [Part 4] The Best Experimental Rock Albums of All Time.md deleted file mode 100644 index dfb1e8763bc6a50782d67488f600c577b4f84a0b..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Avant-garde Rock Collection [Part 4] The Best Experimental Rock Albums of All Time.md +++ /dev/null @@ -1,18 +0,0 @@ -
-

The pivotal development behind the rise of avant-garde rock was strong aesthetic posture adopted by the Beatles--then the most popular music act in the world--with the release of Rubber Soul in late 1965. The album represented a turning point in rock history. For the first time, the long-playing record was viewed as a medium for making a coherent artistic statement rather than as a mere collection of singles. Furthermore, the individual tracks displayed a heightened level of songwriting sophistication. The lyrics in songs like "In My Life" and "Norwegian Wood" revealed a maturity hitherto unprecedented in rock. The refined production work by George Martin offered a dazzling array of instrumental colors and performance dynamics.

-

Avant-garde Rock Collection [Part 4]


Download ✔✔✔ https://urloso.com/2uyO3A



-

A dedicated core of musicians--both rock scene insiders and refugees from the serious music sector seeking a larger audience-- immediately took up the baton. Their aesthetic aspirations were nurtured by a slew of newly established record labels dedicated to issuing uncompromising music within the framework of small-market economics. This ethic has remained intact for more than thirty years with the avant-garde movement continuing to be enriched by the incorporation of new conceptual ideas and stylistic influences.

-

In The Society of the Spectacle (1967), Guy Debord said that the financial, commercial, and economic co-optation of the avant-garde into a commodity produced by neoliberal capitalism makes doubtful that avant-garde artists will remain culturally and intellectually relevant to their societies for preferring profit to cultural change and political progress. In The Theory-Death of the Avant-Garde (1991), Paul Mann said that the avant-garde are economically integral to the contemporary institutions of the Establishment, specifically as part of the culture industry.[17] Noting the conceptual shift, theoreticians, such as Matei Calinescu, in Five Faces of Modernity: Modernism, Avant-garde, Decadence, Kitsch, Postmodernism (1987),[18] and Hans Bertens in The Idea of the Postmodern: A History (1995),[19] said that Western culture entered a post-modern time when the modernist ways of thought and action and the production of art have become redundant in a capitalist economy.[20]

-

Avant-garde in music can refer to any form of music working within traditional structures while seeking to breach boundaries in some manner.[26] The term is used loosely to describe the work of any musicians who radically depart from tradition altogether.[27] By this definition, some avant-garde composers of the 20th century include Arnold Schoenberg,[28] Richard Strauss (in his earliest work),[29] Charles Ives,[30] Igor Stravinsky,[28] Anton Webern,[31] Edgard Varèse, Alban Berg,[31] George Antheil (in his earliest works only), Henry Cowell (in his earliest works), Harry Partch, John Cage, Iannis Xenakis,[28] Morton Feldman, Karlheinz Stockhausen,[32] Pauline Oliveros,[33] Philip Glass, Meredith Monk,[33] Laurie Anderson,[33] and Diamanda Galás.[33]

-

The 1960s saw a wave of free and avant-garde music in jazz genre, embodied by artists such as Ornette Coleman, Sun Ra, Albert Ayler, Archie Shepp, John Coltrane and Miles Davis.[35][36] In the rock music of the 1970s, the "art" descriptor was generally understood to mean "aggressively avant-garde" or "pretentiously progressive".[37] Post-punk artists from the late 1970s rejected traditional rock sensibilities in favor of an avant-garde aesthetic.

-

Experimental rock, also called avant-rock, is a subgenre of rock music[2] that pushes the boundaries of common composition and performance technique[11] or which experiments with the basic elements of the genre.[12] Artists aim to liberate and innovate, with some of the genre's distinguishing characteristics being improvisational performances, avant-garde influences, odd instrumentation, opaque lyrics (or instrumentals), unorthodox structures and rhythms, and an underlying rejection of commercial aspirations.[3]

-

-

From its inception, rock music was experimental, but it was not until the late 1960s that rock artists began creating extended and complex compositions through advancements in multitrack recording. In 1967, the genre was as commercially viable as pop music, but by 1970, most of its leading players had incapacitated themselves in some form.[clarification needed] In Germany, the krautrock subgenre merged elements of improvisation and psychedelic rock with electronic music, avant-garde and contemporary classical pieces. Later in the 1970s, significant musical crossbreeding took place in tandem with the developments of punk and new wave, DIY experimentation, and electronic music. Funk, jazz-rock, and fusion rhythms also became integrated into experimental rock music.

-

Although experimentation had always existed in rock music,[nb 1] it was not until the late 1960s that new openings were created from the aesthetic intersecting with the social.[15][jargon] In 1966, the boundaries between pop music and the avant-garde began to blur as rock albums were conceived and executed as distinct, extended statements.[16] Self-taught rock musicians in the middle and late 1960s drew from the work of composers such as John Cage, Karlheinz Stockhausen, and Luciano Berio. Academic Bill Martin writes: "in the case of imitative painters, what came out was almost always merely derivative, whereas in the case of rock music, the result could be quite original, because assimilation, synthesis, and imitation are integral parts of the language of rock."[17]

-

In the late 1960s, groups such as the Mothers of Invention, the Velvet Underground, the Fugs, the Monks, Red Krayola, Soft Machine, Pink Floyd and the Beatles began incorporating elements of avant-garde music, sound collage, and poetry in their work.[24] Historian David Simonelli writes that, further to the Beatles' "Tomorrow Never Knows" (Revolver, 1966), the band's February 1967 double A-side single, pairing "Strawberry Fields Forever" with "Penny Lane", "establish[ed] the Beatles as the most avant-garde [rock] composers of the postwar era".[25] Aside from the Beatles, author Doyle Greene identifies Frank Zappa, the Velvet Underground, Plastic Ono Band, Captain Beefheart & His Magic Band, Pink Floyd, the Soft Machine and Nico as "pioneers of avant-rock".[26][nb 4] In addition, The Quietus' Ben Graham described duos the Silver Apples and Suicide as antecedents of avant-rock.[28] Pitchfork cited Red Krayola as being "likely the most experimental band of the 1960s" on their review of God Bless the Red Krayola and All Who Sail With It.[29]

-

In the opinion of Stuart Rosenberg, the first "noteworthy" experimental rock group was the Mothers of Invention, led by composer Frank Zappa.[2] Greene recognises the group's debut album, Freak Out!, as marking the "emergence of the 'avant-rock' studio album" at a time when Warhol's presentation of the Velvet Underground's shows was redefining the parameters of a rock concert.[30] According to author Kelly Fisher Lowe, Zappa "set the tone" for experimental rock with the way he incorporated "countertextural aspects ... calling attention to the very recordedness of the album".[31] This was reflected in other contemporary experimental rock LPs, such as the Beach Boys' Pet Sounds and Smile, the Who's The Who Sell Out (1967) and Tommy (1969), and the Beatles' Sgt. Pepper's Lonely Hearts Club Band (1967).[31] The Velvet Underground were a "groundbreaking group in experimental rock", according to Rosenberg, "even further out of step with popular culture than the early recordings of the Mothers of Invention".[32] The band were playing experimental rock in 1965 before other significant countercultural rock scenes had developed,[33] pioneering avant-rock through their integration of minimalist rock and avant-garde ideas.[34][nb 5]

-

In the late 1960s and early 1970s, Germany's "krautrock" scene (also referred to as kosmische or elektronische musik) saw bands develop a form of experimental rock[6][42] that drew on rock sources, such as the Velvet Underground and Frank Zappa, as well as wider avant-garde influences.[24] Groups such as Can, Faust, Neu!, Amon Düül II, Ash Ra Tempel, Kraftwerk, Tangerine Dream, and Popol Vuh merged elements of psychedelic rock with electronic music, funk rhythms, jazz improvisation, and avant-garde and contemporary classical compositions,[43][42] as well as new electronic instrumentation.[24] The ideas of minimalism and composers such as Stockhausen would be particularly influential.[24] The movement was partly born out of the student movements of 1968, as German youth sought a unique countercultural identity[42][24] and wanted to develop a form of German music that was distinct from the mainstream music of the period.[6]

-

Ummagumma is the fourth album by English rock band Pink Floyd. It is a double album and it was released on 7 November 1969 by Harvest Records.[4] The first disc consists of live recordings from concerts at Mothers Club in Birmingham and the College of Commerce in Manchester that contained part of their normal set list of the time, while the second contains solo compositions by each member of the band recorded at EMI Studios (now Abbey Road Studios).[5][6] The artwork was designed by regular Floyd collaborators Hipgnosis and features a number of pictures of the band combined to give a Droste effect. It was the last album cover to feature the band.

-

The sequence of songs that emerged on the record revealed a growing intention to make albums that were not merely a gathering of hit 45s plus supporting material, but a collection that took the notion of the long player into a thrillingly groundbreaking phase: individual examples of technical invention that were never going to trouble the Top 40 panels but were part of a longer listening experience for a maturing audience.

aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/bioriAsaeru/text-to-voice/Download Latest Macos High Sierra How to Get the Most Out of Your Mac.md b/spaces/bioriAsaeru/text-to-voice/Download Latest Macos High Sierra How to Get the Most Out of Your Mac.md deleted file mode 100644 index be654bd44fede17832306b20653271a20ac2b830..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Download Latest Macos High Sierra How to Get the Most Out of Your Mac.md +++ /dev/null @@ -1,13 +0,0 @@ -
-

After the download is complete, the installer will open automatically and ask you whether to install it. If the current macOS is higher than macOS High Sierra, you should decline. Otherwise, the installer will be deleted.

-

Package binaries for R versions older than 3.2.0 are only available from the CRAN archive so users of such versions should adjust the CRAN mirror setting ( -archive.r-project.org) accordingly.R 4.2.2 "Innocent and Trusting" released on 2022/10/31 Please check the integrity of the downloaded package by checking the signature:
pkgutil --check-signature R-4.2.2.pkg
in the Terminal application. If Apple tools are not avaiable you can check the SHA1 checksum of the downloaded image:
openssl sha1 R-4.2.2.pkg
Latest release:R-4.2.2-arm64.pkg (notarized and signed)
SHA1-hash: c3bb657ca6912b9b98e254f63434a365da26848f
(ca. 86MB) for M1 and higher Macs only! R 4.2.2 binary for macOS 11 (Big Sur) and higher, Apple silicon arm64 build, signed and notarized package.
Contains R 4.2.2 framework, R.app GUI 1.79 for Apple silicon Macs (M1 and higher), Tcl/Tk 8.6.12 X11 libraries and Texinfo 6.8.
Important: this version does NOT work on older Intel-based Macs - see below for Intel version.
Note: the use of X11 (including tcltk) requires XQuartz (version 2.8.1 or later). Always re-install XQuartz when upgrading your macOS to a new major version.This release uses Xcode 13.1 and experimental GNU Fortran 12 arm64 fork. If you wish to compile R packages which contain Fortran code, you may need to download GNU Fortran for arm64 from -project.org/tools. Any external libraries and tools are expected to live in /opt/R/arm64 to not conflict with Intel-based software and this build will not use /usr/local to avoid such conflicts (see the tools page for more details).
R-4.2.2.pkg (notarized and signed)
SHA1-hash: 99b8d184f855e630ac950ca4e62cb7fc9a1f7b2e
(ca. 87MB) for Intel Macs R 4.2.2 binary for macOS 10.13 (High Sierra) and higher, Intel 64-bit (older Macs) build, signed and notarized package.
Contains R 4.2.2 framework, R.app GUI 1.79 in 64-bit for Intel Macs, Tcl/Tk 8.6.6 X11 libraries and Texinfo 6.7. The latter two components are optional and can be ommitted when choosing "custom install", they are only needed if you want to use the tcltk R package or build package documentation from sources.Note: the use of X11 (including tcltk) requires XQuartz to be installed (version 2.7.11 or later) since it is no longer part of macOS. Always re-install XQuartz when upgrading your macOS to a new major version.This release supports Intel Macs, but it is also known to work using Rosetta2 on M1-based Macs. For native Apple silicon arm64 binary see above.Important: this release uses Xcode 12.4 and GNU Fortran 8.2. If you wish to compile R packages from sources, you may need to download GNU Fortran 8.2 - see the tools directory.
NEWS (for Mac GUI)News features and changes in the R.app Mac GUI

Mac-GUI-1.78.tar.gz
SHA1-hash: 23b3c41b7eb771640fd504a75e5782792dddb2bcSources for the R.app GUI 1.78 for macOS. This file is only needed if you want to join the development of the GUI (see also Mac-GUI repository), it is not intended for regular users. Read the INSTALL file for further instructions.

Note: Previous R versions for El Capitan can be found in the el-capitan/base directory.
Binaries for legacy OS X systems: R-3.6.3.nn.pkg (signed)
SHA1-hash: c462c9b1f9b45d778f05b8d9aa25a9123b3557c4
(ca. 77MB) R 3.6.3 binary for OS X 10.11 (El Capitan) and higher, signed package. Contains R 3.6.3 framework, R.app GUI 1.70 in 64-bit for Intel Macs, Tcl/Tk 8.6.6 X11 libraries and Texinfo 5.2. The latter two components are optional and can be ommitted when choosing "custom install", they are only needed if you want to use the tcltk R package or build package documentation from sources. R-3.3.3.pkg
MD5-hash: 893ba010f303e666e19f86e4800f1fbf
SHA1-hash: 5ae71b000b15805f95f38c08c45972d51ce3d027
(ca. 71MB)R 3.3.3 binary for Mac OS X 10.9 (Mavericks) and higher, signed package. Contains R 3.3.3 framework, R.app GUI 1.69 in 64-bit for Intel Macs, Tcl/Tk 8.6.0 X11 libraries and Texinfo 5.2. The latter two components are optional and can be ommitted when choosing "custom install", it is only needed if you want to use the tcltk R package or build package documentation from sources.Note: the use of X11 (including tcltk) requires XQuartz to be installed since it is no longer part of OS X. Always re-install XQuartz when upgrading your OS X to a new major version. R-3.2.1-snowleopard.pkg
MD5-hash: 58fe9d01314d9cb75ff80ccfb914fd65
SHA1-hash: be6e91db12bac22a324f0cb51c7efa9063ece0d0
(ca. 68MB)R 3.2.1 legacy binary for Mac OS X 10.6 (Snow Leopard) - 10.8 (Mountain Lion), signed package. Contains R 3.2.1 framework, R.app GUI 1.66 in 64-bit for Intel Macs.
This package contains the R framework, 64-bit GUI (R.app), Tcl/Tk 8.6.0 X11 libraries and Texinfop 5.2. GNU Fortran is NOT included (needed if you want to compile packages from sources that contain FORTRAN code) please see the tools directory.
NOTE: the binary support for OS X before Mavericks is being phased out, we do not expect further releases! The new R.app Cocoa GUI has been written by Simon Urbanek and Stefano Iacus with contributions from many developers and translators world-wide, see "About R" in the GUI.Subdirectories: tools Additional tools necessary for building R for Mac OS X:
Universal GNU Fortran compiler for Mac OS X (see R for Mac tools page for details). base Binaries of R builds for macOS 10.13 or higher (High Sierra), Intel build contrib Binaries of package builds for macOS 10.13 or higher (High Sierra), Intel build big-sur-arm64 Binaries for macOS 11 or higher (Big Sur) for arm64-based Macs (aka Apple silicon such as the M1 chip) el-capitan Binaries of package builds for OS X 10.11 or higher (El Capitan build) mavericks Binaries of package builds for Mac OS X 10.9 or higher (Mavericks build) old Previously released R versions for Mac OS X You may also want to read the R FAQ and R for Mac OS X FAQ. For discussion of Mac-related topics and reporting Mac-specific bugs, please use the R-SIG-Mac mailing list.Information, tools and most recent daily builds of the R GUI, R-patched and R-devel can be found at -project.org/. Please visit that page especially during beta stages to help us test the macOS binaries before final release!
Package maintainers should visit CRAN check summary page to see whether their package is compatible with the current build of R for macOS.Binary libraries for dependencies not present here are available from -project.org/bin and corresponding sources at -project.org/src.Last modified: 2022/10/31, by Simon Urbanek

-

Download Latest Macos High Sierra


DOWNLOAD ►►►►► https://urloso.com/2uyOvg



-

Before you run Digital Performer with High Sierra, be sure to download and install Version 9.52 at the link above (or later versions when they become available at motu.com/download). High Sierra operation requires DP 9.52 or higher.
The v9.52 read me is here.

-

Current versions of all MOTU software products and hardware drivers available at motu.com/download (latest versions) appear to be compatible with High Sierra, although final compatibility testing is still on-going.

-

If you own one of the pro audio models listed below, be sure to download and install the very latest shipping drivers. You must install these latest drivers before you can use your MOTU product listed below with High Sierra.

-

If you own one of the USB-equipped MOTU audio or MIDI interfaces listed below, be sure to download and install the very latest shipping drivers. You must install these latest drivers before you can use your MOTU product listed below with High Sierra.

-

CCC 6 is the latest version available. Users running Catalina (10.15), Big Sur (11.*), Monterey (12.*), or Ventura (13.*) should use this version of CCC. If you are having trouble downloading CCC from the link above, try this alternate download location.

-

Internet Recovery Mode downloads the latest compatible version of macOS or OS X over the Internet and installs it to your hard drive. The entire process may take several hours depending on the quality of your Internet connection.

-

The Java for macOS 2012-006 update from Apple uninstalls the Apple-provided Java applet plug-in from all web browsers. You can download the latest version of Java from Java SE Downloads, which has improved security, reliability, and compatibility.

aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/bookbot/Grad-TTS-Weildan-Playground/Grad-TTS/hifi-gan/env.py b/spaces/bookbot/Grad-TTS-Weildan-Playground/Grad-TTS/hifi-gan/env.py deleted file mode 100644 index 91b0b5391d9d5c226861fd76581d82f67670c2a7..0000000000000000000000000000000000000000 --- a/spaces/bookbot/Grad-TTS-Weildan-Playground/Grad-TTS/hifi-gan/env.py +++ /dev/null @@ -1,17 +0,0 @@ -""" from https://github.com/jik876/hifi-gan """ - -import os -import shutil - - -class AttrDict(dict): - def __init__(self, *args, **kwargs): - super(AttrDict, self).__init__(*args, **kwargs) - self.__dict__ = self - - -def build_env(config, config_name, path): - t_path = os.path.join(path, config_name) - if config != t_path: - os.makedirs(path, exist_ok=True) - shutil.copyfile(config, os.path.join(path, config_name)) diff --git a/spaces/brayden-gg/decoupled-style-descriptors/SynthesisNetwork.py b/spaces/brayden-gg/decoupled-style-descriptors/SynthesisNetwork.py deleted file mode 100644 index 75502a8e5fa24c5dbef598f9e8196a6d17a777d6..0000000000000000000000000000000000000000 --- a/spaces/brayden-gg/decoupled-style-descriptors/SynthesisNetwork.py +++ /dev/null @@ -1,1659 +0,0 @@ -import torch -import torch.nn as nn -from torch.distributions import MultivariateNormal -import math -import numpy as np -from helper import gaussian_2d -from config.GlobalVariables import * - -class SynthesisNetwork(nn.Module): - def __init__(self, weight_dim=512, num_layers=3, scale_sd=1, clamp_mdn=0, sentence_loss=True, word_loss=True, segment_loss=True, TYPE_A=True, TYPE_B=True, TYPE_C=True, TYPE_D=True, ORIGINAL=True, REC=True): - super(SynthesisNetwork, self).__init__() - self.num_mixtures = 20 - self.num_layers = num_layers - self.weight_dim = weight_dim - self.device = 'cuda' if torch.cuda.is_available() else 'cpu' - - self.sentence_loss = sentence_loss - self.word_loss = word_loss - self.segment_loss = segment_loss - - self.ORIGINAL = ORIGINAL - self.TYPE_A = TYPE_A - self.TYPE_B = TYPE_B - self.TYPE_C = TYPE_C - self.TYPE_D = TYPE_D - self.REC = REC - - self.magic_lstm = nn.LSTM(self.weight_dim, self.weight_dim, batch_first=True, num_layers=self.num_layers) - - self.char_vec_fc_1 = nn.Linear(len(CHARACTERS), self.weight_dim) - self.char_vec_relu_1 = nn.LeakyReLU(negative_slope=0.1) - self.char_lstm_1 = nn.LSTM(self.weight_dim, self.weight_dim, batch_first=True, num_layers=self.num_layers) - self.char_vec_fc2_1 = nn.Linear(self.weight_dim, self.weight_dim * self.weight_dim) - - # inference - self.inf_state_fc1 = nn.Linear(3, self.weight_dim) - self.inf_state_relu = nn.LeakyReLU(negative_slope=0.1) - self.inf_state_lstm = nn.LSTM(self.weight_dim, self.weight_dim, batch_first=True, num_layers=self.num_layers) - self.W_lstm = nn.LSTM(self.weight_dim, self.weight_dim, batch_first=True, num_layers=self.num_layers) - - # generation - self.gen_state_fc1 = nn.Linear(3, self.weight_dim) - self.gen_state_relu = nn.LeakyReLU(negative_slope=0.1) - self.gen_state_lstm1 = nn.LSTM(self.weight_dim, self.weight_dim, batch_first=True, num_layers=self.num_layers) - self.gen_state_lstm2 = nn.LSTM(self.weight_dim * 2, self.weight_dim * 2, batch_first=True, num_layers=self.num_layers) - self.gen_state_fc2 = nn.Linear(self.weight_dim * 2, self.num_mixtures * 6 + 1) - - self.term_fc1 = nn.Linear(self.weight_dim * 2, self.weight_dim) - self.term_relu1 = nn.LeakyReLU(negative_slope=0.1) - self.term_fc2 = nn.Linear(self.weight_dim, self.weight_dim) - self.term_relu2 = nn.LeakyReLU(negative_slope=0.1) - self.term_fc3 = nn.Linear(self.weight_dim, 1) - self.term_sigmoid = nn.Sigmoid() - - self.mdn_sigmoid = nn.Sigmoid() - self.mdn_tanh = nn.Tanh() - self.mdn_softmax = nn.Softmax(dim=1) - self.scale_sd = scale_sd # how much to scale the standard deviation of the gaussians - self.clamp_mdn = clamp_mdn # total percent of disrubution to allow sampling from - - self.mdn_bce_loss = nn.BCEWithLogitsLoss() - self.term_bce_loss = nn.BCEWithLogitsLoss() - - def forward(self, inputs): - [sentence_level_stroke_in, sentence_level_stroke_out, sentence_level_stroke_length, sentence_level_term, sentence_level_char, sentence_level_char_length, word_level_stroke_in, word_level_stroke_out, word_level_stroke_length, word_level_term, word_level_char, word_level_char_length, segment_level_stroke_in, segment_level_stroke_out, segment_level_stroke_length, segment_level_term, segment_level_char, segment_level_char_length] = inputs - - ALL_sentence_W_consistency_loss = [] - - ALL_ORIGINAL_sentence_termination_loss = [] - ALL_ORIGINAL_sentence_loc_reconstruct_loss = [] - ALL_ORIGINAL_sentence_touch_reconstruct_loss = [] - - ALL_TYPE_A_sentence_termination_loss = [] - ALL_TYPE_A_sentence_loc_reconstruct_loss = [] - ALL_TYPE_A_sentence_touch_reconstruct_loss = [] - ALL_TYPE_A_sentence_WC_reconstruct_loss = [] - - ALL_TYPE_B_sentence_termination_loss = [] - ALL_TYPE_B_sentence_loc_reconstruct_loss = [] - ALL_TYPE_B_sentence_touch_reconstruct_loss = [] - ALL_TYPE_B_sentence_WC_reconstruct_loss = [] - - - ALL_word_W_consistency_loss = [] - - ALL_ORIGINAL_word_termination_loss = [] - ALL_ORIGINAL_word_loc_reconstruct_loss = [] - ALL_ORIGINAL_word_touch_reconstruct_loss = [] - - ALL_TYPE_A_word_termination_loss = [] - ALL_TYPE_A_word_loc_reconstruct_loss = [] - ALL_TYPE_A_word_touch_reconstruct_loss = [] - ALL_TYPE_A_word_WC_reconstruct_loss = [] - - ALL_TYPE_B_word_termination_loss = [] - ALL_TYPE_B_word_loc_reconstruct_loss = [] - ALL_TYPE_B_word_touch_reconstruct_loss = [] - ALL_TYPE_B_word_WC_reconstruct_loss = [] - - ALL_TYPE_C_word_termination_loss = [] - ALL_TYPE_C_word_loc_reconstruct_loss = [] - ALL_TYPE_C_word_touch_reconstruct_loss = [] - ALL_TYPE_C_word_WC_reconstruct_loss = [] - - ALL_TYPE_D_word_termination_loss = [] - ALL_TYPE_D_word_loc_reconstruct_loss = [] - ALL_TYPE_D_word_touch_reconstruct_loss = [] - ALL_TYPE_D_word_WC_reconstruct_loss = [] - - ALL_word_Wcs_reconstruct_TYPE_A = [] - ALL_word_Wcs_reconstruct_TYPE_B = [] - ALL_word_Wcs_reconstruct_TYPE_C = [] - ALL_word_Wcs_reconstruct_TYPE_D = [] - - SUPER_ALL_segment_W_consistency_loss = [] - - SUPER_ALL_ORIGINAL_segment_termination_loss = [] - SUPER_ALL_ORIGINAL_segment_loc_reconstruct_loss = [] - SUPER_ALL_ORIGINAL_segment_touch_reconstruct_loss = [] - - SUPER_ALL_TYPE_A_segment_termination_loss = [] - SUPER_ALL_TYPE_A_segment_loc_reconstruct_loss = [] - SUPER_ALL_TYPE_A_segment_touch_reconstruct_loss = [] - SUPER_ALL_TYPE_A_segment_WC_reconstruct_loss = [] - - SUPER_ALL_TYPE_B_segment_termination_loss = [] - SUPER_ALL_TYPE_B_segment_loc_reconstruct_loss = [] - SUPER_ALL_TYPE_B_segment_touch_reconstruct_loss = [] - SUPER_ALL_TYPE_B_segment_WC_reconstruct_loss = [] - - SUPER_ALL_segment_Wcs_reconstruct_TYPE_A = [] - SUPER_ALL_segment_Wcs_reconstruct_TYPE_B = [] - - # if self.sentece_loss: - for uid in range(len(sentence_level_stroke_in)): - if self.sentence_loss: - user_sentence_level_stroke_in = sentence_level_stroke_in[uid] - user_sentence_level_stroke_out = sentence_level_stroke_out[uid] - user_sentence_level_stroke_length = sentence_level_stroke_length[uid] - user_sentence_level_term = sentence_level_term[uid] - user_sentence_level_char = sentence_level_char[uid] - user_sentence_level_char_length = sentence_level_char_length[uid] - - sentence_batch_size = len(user_sentence_level_stroke_in) - - sentence_inf_state_out = self.inf_state_fc1(user_sentence_level_stroke_out) - sentence_inf_state_out = self.inf_state_relu(sentence_inf_state_out) - sentence_inf_state_out, (c,h) = self.inf_state_lstm(sentence_inf_state_out) - - sentence_gen_state_out = self.gen_state_fc1(user_sentence_level_stroke_in) - sentence_gen_state_out = self.gen_state_relu(sentence_gen_state_out) - sentence_gen_state_out, (c,h) = self.gen_state_lstm1(sentence_gen_state_out) - - sentence_Ws = [] - sentence_Wc_rec_TYPE_ = [] - sentence_SPLITS = [] - sentence_Cs_1 = [] - sentence_unique_char_matrices_1 = [] - - for sentence_batch_id in range(sentence_batch_size): - curr_seq_len = user_sentence_level_stroke_length[sentence_batch_id][0] - curr_char_len = user_sentence_level_char_length[sentence_batch_id][0] - char_vector = torch.eye(len(CHARACTERS))[user_sentence_level_char[sentence_batch_id][:curr_char_len]].to(self.device) - current_term = user_sentence_level_term[sentence_batch_id][:curr_seq_len].unsqueeze(-1) - split_ids = torch.nonzero(current_term)[:,0] - - char_vector_1 = self.char_vec_fc_1(char_vector) - char_vector_1 = self.char_vec_relu_1(char_vector_1) - - unique_char_matrices_1 = [] - for cid in range(len(char_vector)): - # Tower 1 - unique_char_vector_1 = char_vector_1[cid:cid+1] - unique_char_input_1 = unique_char_vector_1.unsqueeze(0) - unique_char_out_1, (c,h) = self.char_lstm_1(unique_char_input_1) - unique_char_out_1 = unique_char_out_1.squeeze(0) - unique_char_out_1 = self.char_vec_fc2_1(unique_char_out_1) - unique_char_matrix_1 = unique_char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - unique_char_matrix_1 = unique_char_matrix_1.squeeze(1) - unique_char_matrices_1.append(unique_char_matrix_1) - - # Tower 1 - char_out_1 = char_vector_1.unsqueeze(0) - char_out_1, (c,h) = self.char_lstm_1(char_out_1) - char_out_1 = char_out_1.squeeze(0) - char_out_1 = self.char_vec_fc2_1(char_out_1) - char_matrix_1 = char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - char_matrix_1 = char_matrix_1.squeeze(1) - char_matrix_inv_1 = torch.inverse(char_matrix_1) - - W_c_t = sentence_inf_state_out[sentence_batch_id][:curr_seq_len] - W_c = torch.stack([W_c_t[i] for i in split_ids]) - - # W = torch.bmm(char_matrix_inv, W_c.unsqueeze(2)).squeeze(-1) - # C1C2C3W = Wc - # W = C3-1 C2-1 C1-1 Wc - W = torch.bmm(char_matrix_inv_1, - W_c.unsqueeze(2)).squeeze(-1) - sentence_Ws.append(W) - sentence_Wc_rec_TYPE_.append(W_c) - sentence_Cs_1.append(char_matrix_1) - sentence_SPLITS.append(split_ids) - sentence_unique_char_matrices_1.append(unique_char_matrices_1) - - sentence_Ws_stacked = torch.cat(sentence_Ws, 0) - sentence_Ws_reshaped = sentence_Ws_stacked.view([-1,self.weight_dim]) - sentence_W_mean = sentence_Ws_reshaped.mean(0) - sentence_W_mean_repeat = sentence_W_mean.repeat(sentence_Ws_reshaped.size(0),1) - sentence_Ws_consistency_loss = torch.mean(torch.mean(torch.mul(sentence_W_mean_repeat - sentence_Ws_reshaped, sentence_W_mean_repeat - sentence_Ws_reshaped), -1)) - ALL_sentence_W_consistency_loss.append(sentence_Ws_consistency_loss) - - ORIGINAL_sentence_termination_loss = [] - ORIGINAL_sentence_loc_reconstruct_loss = [] - ORIGINAL_sentence_touch_reconstruct_loss = [] - - TYPE_A_sentence_termination_loss = [] - TYPE_A_sentence_loc_reconstruct_loss = [] - TYPE_A_sentence_touch_reconstruct_loss = [] - - TYPE_B_sentence_termination_loss = [] - TYPE_B_sentence_loc_reconstruct_loss = [] - TYPE_B_sentence_touch_reconstruct_loss = [] - - sentence_Wcs_reconstruct_TYPE_A = [] - sentence_Wcs_reconstruct_TYPE_B = [] - - for sentence_batch_id in range(sentence_batch_size): - - sentence_level_gen_encoded = sentence_gen_state_out[sentence_batch_id][:user_sentence_level_stroke_length[sentence_batch_id][0]] - sentence_level_target_eos = user_sentence_level_stroke_out[sentence_batch_id][:user_sentence_level_stroke_length[sentence_batch_id][0]][:,2] - sentence_level_target_x = user_sentence_level_stroke_out[sentence_batch_id][:user_sentence_level_stroke_length[sentence_batch_id][0]][:,0:1] - sentence_level_target_y = user_sentence_level_stroke_out[sentence_batch_id][:user_sentence_level_stroke_length[sentence_batch_id][0]][:,1:2] - sentence_level_target_term = user_sentence_level_term[sentence_batch_id][:user_sentence_level_stroke_length[sentence_batch_id][0]] - - # ORIGINAL - if self.ORIGINAL: - sentence_W_lstm_in_ORIGINAL = [] - curr_id = 0 - for i in range(user_sentence_level_stroke_length[sentence_batch_id][0]): - sentence_W_lstm_in_ORIGINAL.append(sentence_Wc_rec_TYPE_[sentence_batch_id][curr_id]) - if i in sentence_SPLITS[sentence_batch_id]: - curr_id += 1 - sentence_W_lstm_in_ORIGINAL = torch.stack(sentence_W_lstm_in_ORIGINAL) - sentence_Wc_t_ORIGINAL = sentence_W_lstm_in_ORIGINAL - - sentence_gen_lstm2_in_ORIGINAL = torch.cat([sentence_level_gen_encoded, sentence_Wc_t_ORIGINAL], -1) - sentence_gen_lstm2_in_ORIGINAL = sentence_gen_lstm2_in_ORIGINAL.unsqueeze(0) - sentence_gen_out_ORIGINAL,(c,h) = self.gen_state_lstm2(sentence_gen_lstm2_in_ORIGINAL) - sentence_gen_out_ORIGINAL = sentence_gen_out_ORIGINAL.squeeze(0) - - mdn_out_ORIGINAL = self.gen_state_fc2(sentence_gen_out_ORIGINAL) - eos_ORIGINAL = mdn_out_ORIGINAL[:,0:1] - [mu1_ORIGINAL, mu2_ORIGINAL, sig1_ORIGINAL, sig2_ORIGINAL, rho_ORIGINAL, pi_ORIGINAL] = torch.split(mdn_out_ORIGINAL[:,1:], self.num_mixtures, 1) - sig1_ORIGINAL = sig1_ORIGINAL.exp() + 1e-3 - sig2_ORIGINAL = sig2_ORIGINAL.exp() + 1e-3 - rho_ORIGINAL = self.mdn_tanh(rho_ORIGINAL) - pi_ORIGINAL = self.mdn_softmax(pi_ORIGINAL) - - term_out_ORIGINAL = self.term_fc1(sentence_gen_out_ORIGINAL) - term_out_ORIGINAL = self.term_relu1(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_fc2(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_relu2(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_fc3(term_out_ORIGINAL) - term_pred_ORIGINAL = self.term_sigmoid(term_out_ORIGINAL) - - gaussian_ORIGINAL = gaussian_2d(sentence_level_target_x, sentence_level_target_y, mu1_ORIGINAL, mu2_ORIGINAL, sig1_ORIGINAL, sig2_ORIGINAL, rho_ORIGINAL) - loss_gaussian_ORIGINAL = - torch.log(torch.sum(pi_ORIGINAL*gaussian_ORIGINAL, dim=1) + 1e-5) - - ORIGINAL_sentence_term_loss = self.term_bce_loss(term_out_ORIGINAL.squeeze(1), sentence_level_target_term) - ORIGINAL_sentence_loc_loss = torch.mean(loss_gaussian_ORIGINAL) - ORIGINAL_sentence_touch_loss = self.mdn_bce_loss(eos_ORIGINAL.squeeze(1), sentence_level_target_eos) - - ORIGINAL_sentence_termination_loss.append(ORIGINAL_sentence_term_loss) - ORIGINAL_sentence_loc_reconstruct_loss.append(ORIGINAL_sentence_loc_loss) - ORIGINAL_sentence_touch_reconstruct_loss.append(ORIGINAL_sentence_touch_loss) - - # TYPE A - if self.TYPE_A: - sentence_C1 = sentence_Cs_1[sentence_batch_id] - # sentence_Wc_rec_TYPE_A = torch.bmm(sentence_Cs[sentence_batch_id], sentence_W_mean.repeat(sentence_Cs[sentence_batch_id].size(0),1).unsqueeze(2)).squeeze(-1) - sentence_Wc_rec_TYPE_A = torch.bmm(sentence_C1, \ - sentence_W_mean.repeat(sentence_C1.size(0),1).unsqueeze(2)).squeeze(-1) - - sentence_Wcs_reconstruct_TYPE_A.append(sentence_Wc_rec_TYPE_A) - - sentence_W_lstm_in_TYPE_A = [] - curr_id = 0 - for i in range(user_sentence_level_stroke_length[sentence_batch_id][0]): - sentence_W_lstm_in_TYPE_A.append(sentence_Wc_rec_TYPE_A[curr_id]) - if i in sentence_SPLITS[sentence_batch_id]: - curr_id += 1 - sentence_Wc_t_rec_TYPE_A = torch.stack(sentence_W_lstm_in_TYPE_A) - - sentence_gen_lstm2_in_TYPE_A = torch.cat([sentence_level_gen_encoded, sentence_Wc_t_rec_TYPE_A], -1) - sentence_gen_lstm2_in_TYPE_A = sentence_gen_lstm2_in_TYPE_A.unsqueeze(0) - sentence_gen_out_TYPE_A, (c,h) = self.gen_state_lstm2(sentence_gen_lstm2_in_TYPE_A) - sentence_gen_out_TYPE_A = sentence_gen_out_TYPE_A.squeeze(0) - - mdn_out_TYPE_A = self.gen_state_fc2(sentence_gen_out_TYPE_A) - eos_TYPE_A = mdn_out_TYPE_A[:,0:1] - [mu1_TYPE_A, mu2_TYPE_A, sig1_TYPE_A, sig2_TYPE_A, rho_TYPE_A, pi_TYPE_A] = torch.split(mdn_out_TYPE_A[:,1:], self.num_mixtures, 1) - sig1_TYPE_A = sig1_TYPE_A.exp() + 1e-3 - sig2_TYPE_A = sig2_TYPE_A.exp() + 1e-3 - rho_TYPE_A = self.mdn_tanh(rho_TYPE_A) - pi_TYPE_A = self.mdn_softmax(pi_TYPE_A) - term_out_TYPE_A = self.term_fc1(sentence_gen_out_TYPE_A) - term_out_TYPE_A = self.term_relu1(term_out_TYPE_A) - term_out_TYPE_A = self.term_fc2(term_out_TYPE_A) - term_out_TYPE_A = self.term_relu2(term_out_TYPE_A) - term_out_TYPE_A = self.term_fc3(term_out_TYPE_A) - term_pred_TYPE_A = self.term_sigmoid(term_out_TYPE_A) - gaussian_TYPE_A = gaussian_2d(sentence_level_target_x, sentence_level_target_y, mu1_TYPE_A, mu2_TYPE_A, sig1_TYPE_A, sig2_TYPE_A, rho_TYPE_A) - loss_gaussian_TYPE_A = - torch.log(torch.sum(pi_TYPE_A*gaussian_TYPE_A, dim=1) + 1e-5) - - TYPE_A_sentence_term_loss = self.term_bce_loss(term_out_TYPE_A.squeeze(1), sentence_level_target_term) - TYPE_A_sentence_loc_loss = torch.mean(loss_gaussian_TYPE_A) - TYPE_A_sentence_touch_loss = self.mdn_bce_loss(eos_TYPE_A.squeeze(1), sentence_level_target_eos) - - TYPE_A_sentence_termination_loss.append(TYPE_A_sentence_term_loss) - TYPE_A_sentence_loc_reconstruct_loss.append(TYPE_A_sentence_loc_loss) - TYPE_A_sentence_touch_reconstruct_loss.append(TYPE_A_sentence_touch_loss) - - # TYPE B - if self.TYPE_B: - unique_char_matrix_1 = sentence_unique_char_matrices_1[sentence_batch_id] - unique_char_matrices_1 = torch.stack(unique_char_matrix_1) - unique_char_matrices_1 = unique_char_matrices_1.squeeze(1) - - # sentence_W_c_TYPE_B_RAW = torch.bmm(unique_char_matrices, sentence_W_mean.repeat(unique_char_matrices.size(0), 1).unsqueeze(2)).squeeze(-1) - sentence_W_c_TYPE_B_RAW = torch.bmm(unique_char_matrices_1, - sentence_W_mean.repeat(unique_char_matrices_1.size(0), 1).unsqueeze(2)).squeeze(-1) - sentence_W_c_TYPE_B_RAW = sentence_W_c_TYPE_B_RAW.unsqueeze(0) - - sentence_Wc_rec_TYPE_B, (c,h) = self.magic_lstm(sentence_W_c_TYPE_B_RAW) - sentence_Wc_rec_TYPE_B = sentence_Wc_rec_TYPE_B.squeeze(0) - - sentence_Wcs_reconstruct_TYPE_B.append(sentence_Wc_rec_TYPE_B) - - sentence_W_lstm_in_TYPE_B = [] - curr_id = 0 - for i in range(user_sentence_level_stroke_length[sentence_batch_id][0]): - sentence_W_lstm_in_TYPE_B.append(sentence_Wc_rec_TYPE_B[curr_id]) - if i in sentence_SPLITS[sentence_batch_id]: - curr_id += 1 - sentence_Wc_t_rec_TYPE_B = torch.stack(sentence_W_lstm_in_TYPE_B) - - sentence_gen_lstm2_in_TYPE_B = torch.cat([sentence_level_gen_encoded, sentence_Wc_t_rec_TYPE_B], -1) - sentence_gen_lstm2_in_TYPE_B = sentence_gen_lstm2_in_TYPE_B.unsqueeze(0) - sentence_gen_out_TYPE_B, (c,h) = self.gen_state_lstm2(sentence_gen_lstm2_in_TYPE_B) - sentence_gen_out_TYPE_B = sentence_gen_out_TYPE_B.squeeze(0) - - mdn_out_TYPE_B = self.gen_state_fc2(sentence_gen_out_TYPE_B) - eos_TYPE_B = mdn_out_TYPE_B[:,0:1] - [mu1_TYPE_B, mu2_TYPE_B, sig1_TYPE_B, sig2_TYPE_B, rho_TYPE_B, pi_TYPE_B] = torch.split(mdn_out_TYPE_B[:,1:], self.num_mixtures, 1) - sig1_TYPE_B = sig1_TYPE_B.exp() + 1e-3 - sig2_TYPE_B = sig2_TYPE_B.exp() + 1e-3 - rho_TYPE_B = self.mdn_tanh(rho_TYPE_B) - pi_TYPE_B = self.mdn_softmax(pi_TYPE_B) - term_out_TYPE_B = self.term_fc1(sentence_gen_out_TYPE_B) - term_out_TYPE_B = self.term_relu1(term_out_TYPE_B) - term_out_TYPE_B = self.term_fc2(term_out_TYPE_B) - term_out_TYPE_B = self.term_relu2(term_out_TYPE_B) - term_out_TYPE_B = self.term_fc3(term_out_TYPE_B) - term_pred_TYPE_B = self.term_sigmoid(term_out_TYPE_B) - gaussian_TYPE_B = gaussian_2d(sentence_level_target_x, sentence_level_target_y, mu1_TYPE_B, mu2_TYPE_B, sig1_TYPE_B, sig2_TYPE_B, rho_TYPE_B) - loss_gaussian_TYPE_B = - torch.log(torch.sum(pi_TYPE_B*gaussian_TYPE_B, dim=1) + 1e-5) - - TYPE_B_sentence_term_loss = self.term_bce_loss(term_out_TYPE_B.squeeze(1), sentence_level_target_term) - TYPE_B_sentence_loc_loss = torch.mean(loss_gaussian_TYPE_B) - TYPE_B_sentence_touch_loss = self.mdn_bce_loss(eos_TYPE_B.squeeze(1), sentence_level_target_eos) - - TYPE_B_sentence_termination_loss.append(TYPE_B_sentence_term_loss) - TYPE_B_sentence_loc_reconstruct_loss.append(TYPE_B_sentence_loc_loss) - TYPE_B_sentence_touch_reconstruct_loss.append(TYPE_B_sentence_touch_loss) - - if self.ORIGINAL: - ALL_ORIGINAL_sentence_termination_loss.append(torch.mean(torch.stack(ORIGINAL_sentence_termination_loss))) - ALL_ORIGINAL_sentence_loc_reconstruct_loss.append(torch.mean(torch.stack(ORIGINAL_sentence_loc_reconstruct_loss))) - ALL_ORIGINAL_sentence_touch_reconstruct_loss.append(torch.mean(torch.stack(ORIGINAL_sentence_touch_reconstruct_loss))) - - if self.TYPE_A: - ALL_TYPE_A_sentence_termination_loss.append(torch.mean(torch.stack(TYPE_A_sentence_termination_loss))) - ALL_TYPE_A_sentence_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_sentence_loc_reconstruct_loss))) - ALL_TYPE_A_sentence_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_sentence_touch_reconstruct_loss))) - - if self.REC: - TYPE_A_sentence_WC_reconstruct_loss = [] - for sentence_batch_id in range(len(sentence_Wc_rec_TYPE_)): - sentence_Wc_ORIGINAL = sentence_Wc_rec_TYPE_[sentence_batch_id] - sentence_Wc_TYPE_A = sentence_Wcs_reconstruct_TYPE_A[sentence_batch_id] - sentence_WC_reconstruct_loss_TYPE_A = torch.mean(torch.mean(torch.mul(sentence_Wc_ORIGINAL - sentence_Wc_TYPE_A, sentence_Wc_ORIGINAL - sentence_Wc_TYPE_A), -1)) - TYPE_A_sentence_WC_reconstruct_loss.append(sentence_WC_reconstruct_loss_TYPE_A) - ALL_TYPE_A_sentence_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_sentence_WC_reconstruct_loss))) - - if self.TYPE_B: - ALL_TYPE_B_sentence_termination_loss.append(torch.mean(torch.stack(TYPE_B_sentence_termination_loss))) - ALL_TYPE_B_sentence_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_sentence_loc_reconstruct_loss))) - ALL_TYPE_B_sentence_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_sentence_touch_reconstruct_loss))) - - if self.REC: - TYPE_B_sentence_WC_reconstruct_loss = [] - for sentence_batch_id in range(len(sentence_Wc_rec_TYPE_)): - sentence_Wc_ORIGINAL = sentence_Wc_rec_TYPE_[sentence_batch_id] - sentence_Wc_TYPE_B = sentence_Wcs_reconstruct_TYPE_B[sentence_batch_id] - sentence_WC_reconstruct_loss_TYPE_B = torch.mean(torch.mean(torch.mul(sentence_Wc_ORIGINAL - sentence_Wc_TYPE_B, sentence_Wc_ORIGINAL - sentence_Wc_TYPE_B), -1)) - TYPE_B_sentence_WC_reconstruct_loss.append(sentence_WC_reconstruct_loss_TYPE_B) - ALL_TYPE_B_sentence_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_sentence_WC_reconstruct_loss))) - - if self.word_loss: - user_word_level_stroke_in = word_level_stroke_in[uid] - user_word_level_stroke_out = word_level_stroke_out[uid] - user_word_level_stroke_length = word_level_stroke_length[uid] - user_word_level_term = word_level_term[uid] - user_word_level_char = word_level_char[uid] - user_word_level_char_length = word_level_char_length[uid] - - word_batch_size = len(user_word_level_stroke_in) - - word_inf_state_out = self.inf_state_fc1(user_word_level_stroke_out) - word_inf_state_out = self.inf_state_relu(word_inf_state_out) - word_inf_state_out, (c,h) = self.inf_state_lstm(word_inf_state_out) - - word_gen_state_out = self.gen_state_fc1(user_word_level_stroke_in) - word_gen_state_out = self.gen_state_relu(word_gen_state_out) - word_gen_state_out, (c,h) = self.gen_state_lstm1(word_gen_state_out) - - word_Ws = [] - word_Wc_rec_ORIGINAL = [] - word_SPLITS = [] - word_Cs_1 = [] - word_unique_char_matrices_1 = [] - - W_C_ORIGINALS = [] - for word_batch_id in range(word_batch_size): - curr_seq_len = user_word_level_stroke_length[word_batch_id][0] - curr_char_len = user_word_level_char_length[word_batch_id][0] - char_vector = torch.eye(len(CHARACTERS))[user_word_level_char[word_batch_id][:curr_char_len]].to(self.device) - current_term = user_word_level_term[word_batch_id][:curr_seq_len].unsqueeze(-1) - split_ids = torch.nonzero(current_term)[:,0] - - char_vector_1 = self.char_vec_fc_1(char_vector) - char_vector_1 = self.char_vec_relu_1(char_vector_1) - - unique_char_matrices_1 = [] - for cid in range(len(char_vector)): - # Tower 1 - unique_char_vector_1 = char_vector_1[cid:cid+1] - unique_char_input_1 = unique_char_vector_1.unsqueeze(0) - unique_char_out_1, (c,h) = self.char_lstm_1(unique_char_input_1) - unique_char_out_1 = unique_char_out_1.squeeze(0) - unique_char_out_1 = self.char_vec_fc2_1(unique_char_out_1) - unique_char_matrix_1 = unique_char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - unique_char_matrix_1 = unique_char_matrix_1.squeeze(1) - unique_char_matrices_1.append(unique_char_matrix_1) - - # Tower 1 - char_out_1 = char_vector_1.unsqueeze(0) - char_out_1, (c,h) = self.char_lstm_1(char_out_1) - char_out_1 = char_out_1.squeeze(0) - char_out_1 = self.char_vec_fc2_1(char_out_1) - char_matrix_1 = char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - char_matrix_1 = char_matrix_1.squeeze(1) - char_matrix_inv_1 = torch.inverse(char_matrix_1) - - W_c_t = word_inf_state_out[word_batch_id][:curr_seq_len] - W_c = torch.stack([W_c_t[i] for i in split_ids]) - - W_C_ORIGINAL = {} - for i in range(curr_char_len): - sub_s = "".join(CHARACTERS[i] for i in user_word_level_char[word_batch_id][:i+1]) - W_C_ORIGINAL[sub_s] = [W_c[i]] - W_C_ORIGINALS.append(W_C_ORIGINAL) - - # W = torch.bmm(char_matrix_inv, W_c.unsqueeze(2)).squeeze(-1) - W = torch.bmm(char_matrix_inv_1, - W_c.unsqueeze(2)).squeeze(-1) - word_Ws.append(W) - word_Wc_rec_ORIGINAL.append(W_c) - word_SPLITS.append(split_ids) - # word_Cs.append(char_matrix) - # word_unique_char_matrices.append(unique_char_matrices) - word_Cs_1.append(char_matrix_1) - word_unique_char_matrices_1.append(unique_char_matrices_1) - - word_Ws_stacked = torch.cat(word_Ws, 0) - word_Ws_reshaped = word_Ws_stacked.view([-1,self.weight_dim]) - word_W_mean = word_Ws_reshaped.mean(0) - word_Ws_reshaped_mean_repeat = word_W_mean.repeat(word_Ws_reshaped.size(0),1) - word_Ws_consistency_loss = torch.mean(torch.mean(torch.mul(word_Ws_reshaped_mean_repeat - word_Ws_reshaped, word_Ws_reshaped_mean_repeat - word_Ws_reshaped), -1)) - ALL_word_W_consistency_loss.append(word_Ws_consistency_loss) - - # word - ORIGINAL_word_termination_loss = [] - ORIGINAL_word_loc_reconstruct_loss = [] - ORIGINAL_word_touch_reconstruct_loss = [] - - TYPE_A_word_termination_loss = [] - TYPE_A_word_loc_reconstruct_loss = [] - TYPE_A_word_touch_reconstruct_loss = [] - - TYPE_B_word_termination_loss = [] - TYPE_B_word_loc_reconstruct_loss = [] - TYPE_B_word_touch_reconstruct_loss = [] - - TYPE_C_word_termination_loss = [] - TYPE_C_word_loc_reconstruct_loss = [] - TYPE_C_word_touch_reconstruct_loss = [] - - TYPE_D_word_termination_loss = [] - TYPE_D_word_loc_reconstruct_loss = [] - TYPE_D_word_touch_reconstruct_loss = [] - - word_Wcs_reconstruct_TYPE_A = [] - word_Wcs_reconstruct_TYPE_B = [] - word_Wcs_reconstruct_TYPE_C = [] - word_Wcs_reconstruct_TYPE_D = [] - - # segment - - ALL_segment_W_consistency_loss = [] - - ALL_ORIGINAL_segment_termination_loss = [] - ALL_ORIGINAL_segment_loc_reconstruct_loss = [] - ALL_ORIGINAL_segment_touch_reconstruct_loss = [] - - ALL_TYPE_A_segment_termination_loss = [] - ALL_TYPE_A_segment_loc_reconstruct_loss = [] - ALL_TYPE_A_segment_touch_reconstruct_loss = [] - ALL_TYPE_A_segment_WC_reconstruct_loss = [] - - ALL_TYPE_B_segment_termination_loss = [] - ALL_TYPE_B_segment_loc_reconstruct_loss = [] - ALL_TYPE_B_segment_touch_reconstruct_loss = [] - ALL_TYPE_B_segment_WC_reconstruct_loss = [] - - ALL_segment_Wcs_reconstruct_TYPE_A = [] - ALL_segment_Wcs_reconstruct_TYPE_B = [] - - W_C_SEGMENTS = [] - W_C_UNIQUES = [] - for word_batch_id in range(word_batch_size): - - word_level_gen_encoded = word_gen_state_out[word_batch_id][:user_word_level_stroke_length[word_batch_id][0]] - word_level_target_eos = user_word_level_stroke_out[word_batch_id][:user_word_level_stroke_length[word_batch_id][0]][:,2] - word_level_target_x = user_word_level_stroke_out[word_batch_id][:user_word_level_stroke_length[word_batch_id][0]][:,0:1] - word_level_target_y = user_word_level_stroke_out[word_batch_id][:user_word_level_stroke_length[word_batch_id][0]][:,1:2] - word_level_target_term = user_word_level_term[word_batch_id][:user_word_level_stroke_length[word_batch_id][0]] - - # ORIGINAL - if self.ORIGINAL: - word_W_lstm_in_ORIGINAL = [] - curr_id = 0 - for i in range(user_word_level_stroke_length[word_batch_id][0]): - word_W_lstm_in_ORIGINAL.append(word_Wc_rec_ORIGINAL[word_batch_id][curr_id]) - if i in word_SPLITS[word_batch_id]: - curr_id += 1 - word_W_lstm_in_ORIGINAL = torch.stack(word_W_lstm_in_ORIGINAL) - word_Wc_t_ORIGINAL = word_W_lstm_in_ORIGINAL - - word_gen_lstm2_in_ORIGINAL = torch.cat([word_level_gen_encoded, word_Wc_t_ORIGINAL], -1) - word_gen_lstm2_in_ORIGINAL = word_gen_lstm2_in_ORIGINAL.unsqueeze(0) - word_gen_out_ORIGINAL,(c,h) = self.gen_state_lstm2(word_gen_lstm2_in_ORIGINAL) - word_gen_out_ORIGINAL = word_gen_out_ORIGINAL.squeeze(0) - - mdn_out_ORIGINAL = self.gen_state_fc2(word_gen_out_ORIGINAL) - eos_ORIGINAL = mdn_out_ORIGINAL[:,0:1] - [mu1_ORIGINAL, mu2_ORIGINAL, sig1_ORIGINAL, sig2_ORIGINAL, rho_ORIGINAL, pi_ORIGINAL] = torch.split(mdn_out_ORIGINAL[:,1:], self.num_mixtures, 1) - sig1_ORIGINAL = sig1_ORIGINAL.exp() + 1e-3 - sig2_ORIGINAL = sig2_ORIGINAL.exp() + 1e-3 - rho_ORIGINAL = self.mdn_tanh(rho_ORIGINAL) - pi_ORIGINAL = self.mdn_softmax(pi_ORIGINAL) - - term_out_ORIGINAL = self.term_fc1(word_gen_out_ORIGINAL) - term_out_ORIGINAL = self.term_relu1(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_fc2(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_relu2(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_fc3(term_out_ORIGINAL) - term_pred_ORIGINAL = self.term_sigmoid(term_out_ORIGINAL) - - gaussian_ORIGINAL = gaussian_2d(word_level_target_x, word_level_target_y, mu1_ORIGINAL, mu2_ORIGINAL, sig1_ORIGINAL, sig2_ORIGINAL, rho_ORIGINAL) - loss_gaussian_ORIGINAL = - torch.log(torch.sum(pi_ORIGINAL*gaussian_ORIGINAL, dim=1) + 1e-5) - - ORIGINAL_word_term_loss = self.term_bce_loss(term_out_ORIGINAL.squeeze(1), word_level_target_term) - ORIGINAL_word_loc_loss = torch.mean(loss_gaussian_ORIGINAL) - ORIGINAL_word_touch_loss = self.mdn_bce_loss(eos_ORIGINAL.squeeze(1), word_level_target_eos) - - ORIGINAL_word_termination_loss.append(ORIGINAL_word_term_loss) - ORIGINAL_word_loc_reconstruct_loss.append(ORIGINAL_word_loc_loss) - ORIGINAL_word_touch_reconstruct_loss.append(ORIGINAL_word_touch_loss) - - # TYPE A - if self.TYPE_A: - word_C1 = word_Cs_1[word_batch_id] - word_Wc_rec_TYPE_A = torch.bmm(word_C1, - word_W_mean.repeat(word_C1.size(0),1).unsqueeze(2)).squeeze(-1) - - word_Wcs_reconstruct_TYPE_A.append(word_Wc_rec_TYPE_A) - - word_W_lstm_in_TYPE_A = [] - curr_id = 0 - for i in range(user_word_level_stroke_length[word_batch_id][0]): - word_W_lstm_in_TYPE_A.append(word_Wc_rec_TYPE_A[curr_id]) - if i in word_SPLITS[word_batch_id]: - curr_id += 1 - word_Wc_t_rec_TYPE_A = torch.stack(word_W_lstm_in_TYPE_A) - - word_gen_lstm2_in_TYPE_A = torch.cat([word_level_gen_encoded, word_Wc_t_rec_TYPE_A], -1) - word_gen_lstm2_in_TYPE_A = word_gen_lstm2_in_TYPE_A.unsqueeze(0) - word_gen_out_TYPE_A, (c,h) = self.gen_state_lstm2(word_gen_lstm2_in_TYPE_A) - word_gen_out_TYPE_A = word_gen_out_TYPE_A.squeeze(0) - - mdn_out_TYPE_A = self.gen_state_fc2(word_gen_out_TYPE_A) - eos_TYPE_A = mdn_out_TYPE_A[:,0:1] - [mu1_TYPE_A, mu2_TYPE_A, sig1_TYPE_A, sig2_TYPE_A, rho_TYPE_A, pi_TYPE_A] = torch.split(mdn_out_TYPE_A[:,1:], self.num_mixtures, 1) - sig1_TYPE_A = sig1_TYPE_A.exp() + 1e-3 - sig2_TYPE_A = sig2_TYPE_A.exp() + 1e-3 - rho_TYPE_A = self.mdn_tanh(rho_TYPE_A) - pi_TYPE_A = self.mdn_softmax(pi_TYPE_A) - term_out_TYPE_A = self.term_fc1(word_gen_out_TYPE_A) - term_out_TYPE_A = self.term_relu1(term_out_TYPE_A) - term_out_TYPE_A = self.term_fc2(term_out_TYPE_A) - term_out_TYPE_A = self.term_relu2(term_out_TYPE_A) - term_out_TYPE_A = self.term_fc3(term_out_TYPE_A) - term_pred_TYPE_A = self.term_sigmoid(term_out_TYPE_A) - gaussian_TYPE_A = gaussian_2d(word_level_target_x, word_level_target_y, mu1_TYPE_A, mu2_TYPE_A, sig1_TYPE_A, sig2_TYPE_A, rho_TYPE_A) - loss_gaussian_TYPE_A = - torch.log(torch.sum(pi_TYPE_A*gaussian_TYPE_A, dim=1) + 1e-5) - - TYPE_A_word_term_loss = self.term_bce_loss(term_out_TYPE_A.squeeze(1), word_level_target_term) - TYPE_A_word_loc_loss = torch.mean(loss_gaussian_TYPE_A) - TYPE_A_word_touch_loss = self.mdn_bce_loss(eos_TYPE_A.squeeze(1), word_level_target_eos) - - TYPE_A_word_termination_loss.append(TYPE_A_word_term_loss) - TYPE_A_word_loc_reconstruct_loss.append(TYPE_A_word_loc_loss) - TYPE_A_word_touch_reconstruct_loss.append(TYPE_A_word_touch_loss) - - # TYPE B - if self.TYPE_B: - unique_char_matrix_1 = word_unique_char_matrices_1[word_batch_id] - unique_char_matrices_1 = torch.stack(unique_char_matrix_1) - unique_char_matrices_1 = unique_char_matrices_1.squeeze(1) - - # word_W_c_TYPE_B_RAW = torch.bmm(unique_char_matrices, word_W_mean.repeat(unique_char_matrices.size(0), 1).unsqueeze(2)).squeeze(-1) - word_W_c_TYPE_B_RAW = torch.bmm(unique_char_matrices_1, - word_W_mean.repeat(unique_char_matrices_1.size(0), 1).unsqueeze(2)).squeeze(-1) - word_W_c_TYPE_B_RAW = word_W_c_TYPE_B_RAW.unsqueeze(0) - - word_Wc_rec_TYPE_B, (c,h) = self.magic_lstm(word_W_c_TYPE_B_RAW) - word_Wc_rec_TYPE_B = word_Wc_rec_TYPE_B.squeeze(0) - - word_Wcs_reconstruct_TYPE_B.append(word_Wc_rec_TYPE_B) - - word_W_lstm_in_TYPE_B = [] - curr_id = 0 - for i in range(user_word_level_stroke_length[word_batch_id][0]): - word_W_lstm_in_TYPE_B.append(word_Wc_rec_TYPE_B[curr_id]) - if i in word_SPLITS[word_batch_id]: - curr_id += 1 - word_Wc_t_rec_TYPE_B = torch.stack(word_W_lstm_in_TYPE_B) - word_gen_lstm2_in_TYPE_B = torch.cat([word_level_gen_encoded, word_Wc_t_rec_TYPE_B], -1) - word_gen_lstm2_in_TYPE_B = word_gen_lstm2_in_TYPE_B.unsqueeze(0) - word_gen_out_TYPE_B, (c,h) = self.gen_state_lstm2(word_gen_lstm2_in_TYPE_B) - word_gen_out_TYPE_B = word_gen_out_TYPE_B.squeeze(0) - - mdn_out_TYPE_B = self.gen_state_fc2(word_gen_out_TYPE_B) - eos_TYPE_B = mdn_out_TYPE_B[:,0:1] - [mu1_TYPE_B, mu2_TYPE_B, sig1_TYPE_B, sig2_TYPE_B, rho_TYPE_B, pi_TYPE_B] = torch.split(mdn_out_TYPE_B[:,1:], self.num_mixtures, 1) - sig1_TYPE_B = sig1_TYPE_B.exp() + 1e-3 - sig2_TYPE_B = sig2_TYPE_B.exp() + 1e-3 - rho_TYPE_B = self.mdn_tanh(rho_TYPE_B) - pi_TYPE_B = self.mdn_softmax(pi_TYPE_B) - term_out_TYPE_B = self.term_fc1(word_gen_out_TYPE_B) - term_out_TYPE_B = self.term_relu1(term_out_TYPE_B) - term_out_TYPE_B = self.term_fc2(term_out_TYPE_B) - term_out_TYPE_B = self.term_relu2(term_out_TYPE_B) - term_out_TYPE_B = self.term_fc3(term_out_TYPE_B) - term_pred_TYPE_B = self.term_sigmoid(term_out_TYPE_B) - gaussian_TYPE_B = gaussian_2d(word_level_target_x, word_level_target_y, mu1_TYPE_B, mu2_TYPE_B, sig1_TYPE_B, sig2_TYPE_B, rho_TYPE_B) - loss_gaussian_TYPE_B = - torch.log(torch.sum(pi_TYPE_B*gaussian_TYPE_B, dim=1) + 1e-5) - - TYPE_B_word_term_loss = self.term_bce_loss(term_out_TYPE_B.squeeze(1), word_level_target_term) - TYPE_B_word_loc_loss = torch.mean(loss_gaussian_TYPE_B) - TYPE_B_word_touch_loss = self.mdn_bce_loss(eos_TYPE_B.squeeze(1), word_level_target_eos) - - TYPE_B_word_termination_loss.append(TYPE_B_word_term_loss) - TYPE_B_word_loc_reconstruct_loss.append(TYPE_B_word_loc_loss) - TYPE_B_word_touch_reconstruct_loss.append(TYPE_B_word_touch_loss) - - # TYPE C - # if self.TYPE_C: - user_segment_level_stroke_in = segment_level_stroke_in[uid][word_batch_id] - user_segment_level_stroke_out = segment_level_stroke_out[uid][word_batch_id] - user_segment_level_stroke_length = segment_level_stroke_length[uid][word_batch_id] - user_segment_level_term = segment_level_term[uid][word_batch_id] - user_segment_level_char = segment_level_char[uid][word_batch_id] - user_segment_level_char_length = segment_level_char_length[uid][word_batch_id] - - segment_batch_size = len(user_segment_level_stroke_in) - - segment_inf_state_out = self.inf_state_fc1(user_segment_level_stroke_out) - segment_inf_state_out = self.inf_state_relu(segment_inf_state_out) - segment_inf_state_out, (c,h) = self.inf_state_lstm(segment_inf_state_out) - - segment_gen_state_out = self.gen_state_fc1(user_segment_level_stroke_in) - segment_gen_state_out = self.gen_state_relu(segment_gen_state_out) - segment_gen_state_out, (c,h) = self.gen_state_lstm1(segment_gen_state_out) - - segment_Ws = [] - segment_Wc_rec_ORIGINAL = [] - segment_SPLITS = [] - segment_Cs_1 = [] - segment_unique_char_matrices_1 = [] - - W_C_SEGMENT = {} - - for segment_batch_id in range(segment_batch_size): - curr_seq_len = user_segment_level_stroke_length[segment_batch_id][0] - curr_char_len = user_segment_level_char_length[segment_batch_id][0] - char_vector = torch.eye(len(CHARACTERS))[user_segment_level_char[segment_batch_id][:curr_char_len]].to(self.device) - current_term = user_segment_level_term[segment_batch_id][:curr_seq_len].unsqueeze(-1) - split_ids = torch.nonzero(current_term)[:,0] - - char_vector_1 = self.char_vec_fc_1(char_vector) - char_vector_1 = self.char_vec_relu_1(char_vector_1) - unique_char_matrices_1 = [] - - for cid in range(len(char_vector)): - # Tower 1 - unique_char_vector_1 = char_vector_1[cid:cid+1] - unique_char_input_1 = unique_char_vector_1.unsqueeze(0) - unique_char_out_1, (c,h) = self.char_lstm_1(unique_char_input_1) - unique_char_out_1 = unique_char_out_1.squeeze(0) - unique_char_out_1 = self.char_vec_fc2_1(unique_char_out_1) - unique_char_matrix_1 = unique_char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - unique_char_matrix_1 = unique_char_matrix_1.squeeze(1) - unique_char_matrices_1.append(unique_char_matrix_1) - - # Tower 1 - char_out_1 = char_vector_1.unsqueeze(0) - char_out_1, (c,h) = self.char_lstm_1(char_out_1) - char_out_1 = char_out_1.squeeze(0) - char_out_1 = self.char_vec_fc2_1(char_out_1) - char_matrix_1 = char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - char_matrix_1 = char_matrix_1.squeeze(1) - char_matrix_inv_1 = torch.inverse(char_matrix_1) - - W_c_t = segment_inf_state_out[segment_batch_id][:curr_seq_len] - W_c = torch.stack([W_c_t[i] for i in split_ids]) - - for i in range(curr_char_len): - sub_s = "".join(CHARACTERS[i] for i in user_segment_level_char[segment_batch_id][:i+1]) - if sub_s in W_C_SEGMENT: - W_C_SEGMENT[sub_s].append(W_c[i]) - else: - W_C_SEGMENT[sub_s] = [W_c[i]] - - W = torch.bmm(char_matrix_inv_1, - W_c.unsqueeze(2)).squeeze(-1) - segment_Ws.append(W) - segment_Wc_rec_ORIGINAL.append(W_c) - segment_SPLITS.append(split_ids) - segment_Cs_1.append(char_matrix_1) - segment_unique_char_matrices_1.append(unique_char_matrices_1) - - W_C_SEGMENTS.append(W_C_SEGMENT) - - if self.segment_loss: - segment_Ws_stacked = torch.cat(segment_Ws, 0) - segment_Ws_reshaped = segment_Ws_stacked.view([-1,self.weight_dim]) - segment_W_mean = segment_Ws_reshaped.mean(0) - segment_Ws_reshaped_mean_repeat = segment_W_mean.repeat(segment_Ws_reshaped.size(0),1) - segment_Ws_consistency_loss = torch.mean(torch.mean(torch.mul(segment_Ws_reshaped_mean_repeat - segment_Ws_reshaped, segment_Ws_reshaped_mean_repeat - segment_Ws_reshaped), -1)) - ALL_segment_W_consistency_loss.append(segment_Ws_consistency_loss) - - ORIGINAL_segment_termination_loss = [] - ORIGINAL_segment_loc_reconstruct_loss = [] - ORIGINAL_segment_touch_reconstruct_loss = [] - - TYPE_A_segment_termination_loss = [] - TYPE_A_segment_loc_reconstruct_loss = [] - TYPE_A_segment_touch_reconstruct_loss = [] - - TYPE_B_segment_termination_loss = [] - TYPE_B_segment_loc_reconstruct_loss = [] - TYPE_B_segment_touch_reconstruct_loss = [] - - segment_Wcs_reconstruct_TYPE_A = [] - segment_Wcs_reconstruct_TYPE_B = [] - - for segment_batch_id in range(segment_batch_size): - segment_level_gen_encoded = segment_gen_state_out[segment_batch_id][:user_segment_level_stroke_length[segment_batch_id][0]] - segment_level_target_eos = user_segment_level_stroke_out[segment_batch_id][:user_segment_level_stroke_length[segment_batch_id][0]][:,2] - segment_level_target_x = user_segment_level_stroke_out[segment_batch_id][:user_segment_level_stroke_length[segment_batch_id][0]][:,0:1] - segment_level_target_y = user_segment_level_stroke_out[segment_batch_id][:user_segment_level_stroke_length[segment_batch_id][0]][:,1:2] - segment_level_target_term = user_segment_level_term[segment_batch_id][:user_segment_level_stroke_length[segment_batch_id][0]] - - if self.ORIGINAL: - segment_W_lstm_in_ORIGINAL = [] - curr_id = 0 - for i in range(user_segment_level_stroke_length[segment_batch_id][0]): - segment_W_lstm_in_ORIGINAL.append(segment_Wc_rec_ORIGINAL[segment_batch_id][curr_id]) - if i in segment_SPLITS[segment_batch_id]: - curr_id += 1 - segment_W_lstm_in_ORIGINAL = torch.stack(segment_W_lstm_in_ORIGINAL) - segment_Wc_t_ORIGINAL = segment_W_lstm_in_ORIGINAL - - segment_gen_lstm2_in_ORIGINAL = torch.cat([segment_level_gen_encoded, segment_Wc_t_ORIGINAL], -1) - segment_gen_lstm2_in_ORIGINAL = segment_gen_lstm2_in_ORIGINAL.unsqueeze(0) - segment_gen_out_ORIGINAL,(c,h) = self.gen_state_lstm2(segment_gen_lstm2_in_ORIGINAL) - segment_gen_out_ORIGINAL = segment_gen_out_ORIGINAL.squeeze(0) - - mdn_out_ORIGINAL = self.gen_state_fc2(segment_gen_out_ORIGINAL) - eos_ORIGINAL = mdn_out_ORIGINAL[:,0:1] - [mu1_ORIGINAL, mu2_ORIGINAL, sig1_ORIGINAL, sig2_ORIGINAL, rho_ORIGINAL, pi_ORIGINAL] = torch.split(mdn_out_ORIGINAL[:,1:], self.num_mixtures, 1) - sig1_ORIGINAL = sig1_ORIGINAL.exp() + 1e-3 - sig2_ORIGINAL = sig2_ORIGINAL.exp() + 1e-3 - rho_ORIGINAL = self.mdn_tanh(rho_ORIGINAL) - pi_ORIGINAL = self.mdn_softmax(pi_ORIGINAL) - - term_out_ORIGINAL = self.term_fc1(segment_gen_out_ORIGINAL) - term_out_ORIGINAL = self.term_relu1(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_fc2(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_relu2(term_out_ORIGINAL) - term_out_ORIGINAL = self.term_fc3(term_out_ORIGINAL) - term_pred_ORIGINAL = self.term_sigmoid(term_out_ORIGINAL) - - gaussian_ORIGINAL = gaussian_2d(segment_level_target_x, segment_level_target_y, mu1_ORIGINAL, mu2_ORIGINAL, sig1_ORIGINAL, sig2_ORIGINAL, rho_ORIGINAL) - loss_gaussian_ORIGINAL = - torch.log(torch.sum(pi_ORIGINAL*gaussian_ORIGINAL, dim=1) + 1e-5) - - ORIGINAL_segment_term_loss = self.term_bce_loss(term_out_ORIGINAL.squeeze(1), segment_level_target_term) - ORIGINAL_segment_loc_loss = torch.mean(loss_gaussian_ORIGINAL) - ORIGINAL_segment_touch_loss = self.mdn_bce_loss(eos_ORIGINAL.squeeze(1), segment_level_target_eos) - - ORIGINAL_segment_termination_loss.append(ORIGINAL_segment_term_loss) - ORIGINAL_segment_loc_reconstruct_loss.append(ORIGINAL_segment_loc_loss) - ORIGINAL_segment_touch_reconstruct_loss.append(ORIGINAL_segment_touch_loss) - - # TYPE A - if self.TYPE_A: - segment_C1 = segment_Cs_1[segment_batch_id] - segment_Wc_rec_TYPE_A = torch.bmm(segment_C1, - segment_W_mean.repeat(segment_C1.size(0),1).unsqueeze(2)).squeeze(-1) - segment_Wcs_reconstruct_TYPE_A.append(segment_Wc_rec_TYPE_A) - - segment_W_lstm_in_TYPE_A = [] - curr_id = 0 - for i in range(user_segment_level_stroke_length[segment_batch_id][0]): - segment_W_lstm_in_TYPE_A.append(segment_Wc_rec_TYPE_A[curr_id]) - if i in segment_SPLITS[segment_batch_id]: - curr_id += 1 - segment_Wc_t_rec_TYPE_A = torch.stack(segment_W_lstm_in_TYPE_A) - - segment_gen_lstm2_in_TYPE_A = torch.cat([segment_level_gen_encoded, segment_Wc_t_rec_TYPE_A], -1) - segment_gen_lstm2_in_TYPE_A = segment_gen_lstm2_in_TYPE_A.unsqueeze(0) - segment_gen_out_TYPE_A, (c,h) = self.gen_state_lstm2(segment_gen_lstm2_in_TYPE_A) - segment_gen_out_TYPE_A = segment_gen_out_TYPE_A.squeeze(0) - - mdn_out_TYPE_A = self.gen_state_fc2(segment_gen_out_TYPE_A) - eos_TYPE_A = mdn_out_TYPE_A[:,0:1] - [mu1_TYPE_A, mu2_TYPE_A, sig1_TYPE_A, sig2_TYPE_A, rho_TYPE_A, pi_TYPE_A] = torch.split(mdn_out_TYPE_A[:,1:], self.num_mixtures, 1) - sig1_TYPE_A = sig1_TYPE_A.exp() + 1e-3 - sig2_TYPE_A = sig2_TYPE_A.exp() + 1e-3 - rho_TYPE_A = self.mdn_tanh(rho_TYPE_A) - pi_TYPE_A = self.mdn_softmax(pi_TYPE_A) - term_out_TYPE_A = self.term_fc1(segment_gen_out_TYPE_A) - term_out_TYPE_A = self.term_relu1(term_out_TYPE_A) - term_out_TYPE_A = self.term_fc2(term_out_TYPE_A) - term_out_TYPE_A = self.term_relu2(term_out_TYPE_A) - term_out_TYPE_A = self.term_fc3(term_out_TYPE_A) - term_pred_TYPE_A = self.term_sigmoid(term_out_TYPE_A) - gaussian_TYPE_A = gaussian_2d(segment_level_target_x, segment_level_target_y, mu1_TYPE_A, mu2_TYPE_A, sig1_TYPE_A, sig2_TYPE_A, rho_TYPE_A) - loss_gaussian_TYPE_A = - torch.log(torch.sum(pi_TYPE_A*gaussian_TYPE_A, dim=1) + 1e-5) - - TYPE_A_segment_term_loss = self.term_bce_loss(term_out_TYPE_A.squeeze(1), segment_level_target_term) - TYPE_A_segment_loc_loss = torch.mean(loss_gaussian_TYPE_A) - TYPE_A_segment_touch_loss = self.mdn_bce_loss(eos_TYPE_A.squeeze(1), segment_level_target_eos) - - TYPE_A_segment_termination_loss.append(TYPE_A_segment_term_loss) - TYPE_A_segment_loc_reconstruct_loss.append(TYPE_A_segment_loc_loss) - TYPE_A_segment_touch_reconstruct_loss.append(TYPE_A_segment_touch_loss) - - # TYPE B - if self.TYPE_B: - unique_char_matrix_1 = segment_unique_char_matrices_1[segment_batch_id] - unique_char_matrices_1 = torch.stack(unique_char_matrix_1) - unique_char_matrices_1 = unique_char_matrices_1.squeeze(1) - - # segment_W_c_TYPE_B_RAW = torch.bmm(unique_char_matrices, segment_W_mean.repeat(unique_char_matrices.size(0), 1).unsqueeze(2)).squeeze(-1) - segment_W_c_TYPE_B_RAW = torch.bmm(unique_char_matrices_1, - segment_W_mean.repeat(unique_char_matrices_1.size(0), 1).unsqueeze(2)).squeeze(-1) - segment_W_c_TYPE_B_RAW = segment_W_c_TYPE_B_RAW.unsqueeze(0) - - segment_Wc_rec_TYPE_B, (c,h) = self.magic_lstm(segment_W_c_TYPE_B_RAW) - segment_Wc_rec_TYPE_B = segment_Wc_rec_TYPE_B.squeeze(0) - - segment_Wcs_reconstruct_TYPE_B.append(segment_Wc_rec_TYPE_B) - - segment_W_lstm_in_TYPE_B = [] - curr_id = 0 - for i in range(user_segment_level_stroke_length[segment_batch_id][0]): - segment_W_lstm_in_TYPE_B.append(segment_Wc_rec_TYPE_B[curr_id]) - if i in segment_SPLITS[segment_batch_id]: - curr_id += 1 - segment_Wc_t_rec_TYPE_B = torch.stack(segment_W_lstm_in_TYPE_B) - - segment_gen_lstm2_in_TYPE_B = torch.cat([segment_level_gen_encoded, segment_Wc_t_rec_TYPE_B], -1) - segment_gen_lstm2_in_TYPE_B = segment_gen_lstm2_in_TYPE_B.unsqueeze(0) - segment_gen_out_TYPE_B, (c,h) = self.gen_state_lstm2(segment_gen_lstm2_in_TYPE_B) - segment_gen_out_TYPE_B = segment_gen_out_TYPE_B.squeeze(0) - - mdn_out_TYPE_B = self.gen_state_fc2(segment_gen_out_TYPE_B) - eos_TYPE_B = mdn_out_TYPE_B[:,0:1] - [mu1_TYPE_B, mu2_TYPE_B, sig1_TYPE_B, sig2_TYPE_B, rho_TYPE_B, pi_TYPE_B] = torch.split(mdn_out_TYPE_B[:,1:], self.num_mixtures, 1) - sig1_TYPE_B = sig1_TYPE_B.exp() + 1e-3 - sig2_TYPE_B = sig2_TYPE_B.exp() + 1e-3 - rho_TYPE_B = self.mdn_tanh(rho_TYPE_B) - pi_TYPE_B = self.mdn_softmax(pi_TYPE_B) - term_out_TYPE_B = self.term_fc1(segment_gen_out_TYPE_B) - term_out_TYPE_B = self.term_relu1(term_out_TYPE_B) - term_out_TYPE_B = self.term_fc2(term_out_TYPE_B) - term_out_TYPE_B = self.term_relu2(term_out_TYPE_B) - term_out_TYPE_B = self.term_fc3(term_out_TYPE_B) - term_pred_TYPE_B = self.term_sigmoid(term_out_TYPE_B) - gaussian_TYPE_B = gaussian_2d(segment_level_target_x, segment_level_target_y, mu1_TYPE_B, mu2_TYPE_B, sig1_TYPE_B, sig2_TYPE_B, rho_TYPE_B) - loss_gaussian_TYPE_B = - torch.log(torch.sum(pi_TYPE_B*gaussian_TYPE_B, dim=1) + 1e-5) - - TYPE_B_segment_term_loss = self.term_bce_loss(term_out_TYPE_B.squeeze(1), segment_level_target_term) - TYPE_B_segment_loc_loss = torch.mean(loss_gaussian_TYPE_B) - TYPE_B_segment_touch_loss = self.mdn_bce_loss(eos_TYPE_B.squeeze(1), segment_level_target_eos) - - TYPE_B_segment_termination_loss.append(TYPE_B_segment_term_loss) - TYPE_B_segment_loc_reconstruct_loss.append(TYPE_B_segment_loc_loss) - TYPE_B_segment_touch_reconstruct_loss.append(TYPE_B_segment_touch_loss) - - if self.ORIGINAL: - ALL_ORIGINAL_segment_termination_loss.append(torch.mean(torch.stack(ORIGINAL_segment_termination_loss))) - ALL_ORIGINAL_segment_loc_reconstruct_loss.append(torch.mean(torch.stack(ORIGINAL_segment_loc_reconstruct_loss))) - ALL_ORIGINAL_segment_touch_reconstruct_loss.append(torch.mean(torch.stack(ORIGINAL_segment_touch_reconstruct_loss))) - - if self.TYPE_A: - ALL_TYPE_A_segment_termination_loss.append(torch.mean(torch.stack(TYPE_A_segment_termination_loss))) - ALL_TYPE_A_segment_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_segment_loc_reconstruct_loss))) - ALL_TYPE_A_segment_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_segment_touch_reconstruct_loss))) - - if self.REC: - TYPE_A_segment_WC_reconstruct_loss = [] - for segment_batch_id in range(len(segment_Wc_rec_ORIGINAL)): - segment_Wc_ORIGINAL = segment_Wc_rec_ORIGINAL[segment_batch_id] - segment_Wc_TYPE_A = segment_Wcs_reconstruct_TYPE_A[segment_batch_id] - segment_WC_reconstruct_loss_TYPE_A = torch.mean(torch.mean(torch.mul(segment_Wc_ORIGINAL - segment_Wc_TYPE_A, segment_Wc_ORIGINAL - segment_Wc_TYPE_A), -1)) - TYPE_A_segment_WC_reconstruct_loss.append(segment_WC_reconstruct_loss_TYPE_A) - ALL_TYPE_A_segment_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_segment_WC_reconstruct_loss))) - - if self.TYPE_B: - ALL_TYPE_B_segment_termination_loss.append(torch.mean(torch.stack(TYPE_B_segment_termination_loss))) - ALL_TYPE_B_segment_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_segment_loc_reconstruct_loss))) - ALL_TYPE_B_segment_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_segment_touch_reconstruct_loss))) - - if self.REC: - TYPE_B_segment_WC_reconstruct_loss = [] - for segment_batch_id in range(len(segment_Wc_rec_ORIGINAL)): - segment_Wc_ORIGINAL = segment_Wc_rec_ORIGINAL[segment_batch_id] - segment_Wc_TYPE_B = segment_Wcs_reconstruct_TYPE_B[segment_batch_id] - segment_WC_reconstruct_loss_TYPE_B = torch.mean(torch.mean(torch.mul(segment_Wc_ORIGINAL - segment_Wc_TYPE_B, segment_Wc_ORIGINAL - segment_Wc_TYPE_B), -1)) - TYPE_B_segment_WC_reconstruct_loss.append(segment_WC_reconstruct_loss_TYPE_B) - ALL_TYPE_B_segment_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_segment_WC_reconstruct_loss))) - - if self.TYPE_C: - # target - original_W_c = word_Wc_rec_ORIGINAL[word_batch_id] - word_Wc_rec_TYPE_C = [] - for segment_batch_id in range(len(segment_Wc_rec_ORIGINAL)): - if segment_batch_id == 0: - for each_segment_Wc in segment_Wc_rec_ORIGINAL[segment_batch_id]: - word_Wc_rec_TYPE_C.append(each_segment_Wc) - prev_id = len(word_Wc_rec_TYPE_C) - 1 - else: - prev_original_W_c = original_W_c[prev_id] - for each_segment_Wc in segment_Wc_rec_ORIGINAL[segment_batch_id]: - magic_inp = torch.stack([prev_original_W_c, each_segment_Wc]) - magic_inp = magic_inp.unsqueeze(0) - type_c_out, (c,h) = self.magic_lstm(magic_inp) - type_c_out = type_c_out.squeeze(0) - word_Wc_rec_TYPE_C.append(type_c_out[-1]) - prev_id = len(word_Wc_rec_TYPE_C) - 1 - - word_Wc_rec_TYPE_C = torch.stack(word_Wc_rec_TYPE_C) - word_Wcs_reconstruct_TYPE_C.append(word_Wc_rec_TYPE_C) - - if len(word_Wc_rec_TYPE_C) == len(word_SPLITS[word_batch_id]): - word_W_lstm_in_TYPE_C = [] - curr_id = 0 - for i in range(user_word_level_stroke_length[word_batch_id][0]): - word_W_lstm_in_TYPE_C.append(word_Wc_rec_TYPE_C[curr_id]) - if i in word_SPLITS[word_batch_id]: - curr_id += 1 - word_Wc_t_rec_TYPE_C = torch.stack(word_W_lstm_in_TYPE_C) - - word_gen_lstm2_in_TYPE_C = torch.cat([word_level_gen_encoded, word_Wc_t_rec_TYPE_C], -1) - word_gen_lstm2_in_TYPE_C = word_gen_lstm2_in_TYPE_C.unsqueeze(0) - word_gen_out_TYPE_C, (c,h) = self.gen_state_lstm2(word_gen_lstm2_in_TYPE_C) - word_gen_out_TYPE_C = word_gen_out_TYPE_C.squeeze(0) - - mdn_out_TYPE_C = self.gen_state_fc2(word_gen_out_TYPE_C) - eos_TYPE_C = mdn_out_TYPE_C[:,0:1] - [mu1_TYPE_C, mu2_TYPE_C, sig1_TYPE_C, sig2_TYPE_C, rho_TYPE_C, pi_TYPE_C] = torch.split(mdn_out_TYPE_C[:,1:], self.num_mixtures, 1) - sig1_TYPE_C = sig1_TYPE_C.exp() + 1e-3 - sig2_TYPE_C = sig2_TYPE_C.exp() + 1e-3 - rho_TYPE_C = self.mdn_tanh(rho_TYPE_C) - pi_TYPE_C = self.mdn_softmax(pi_TYPE_C) - term_out_TYPE_C = self.term_fc1(word_gen_out_TYPE_C) - term_out_TYPE_C = self.term_relu1(term_out_TYPE_C) - term_out_TYPE_C = self.term_fc2(term_out_TYPE_C) - term_out_TYPE_C = self.term_relu2(term_out_TYPE_C) - term_out_TYPE_C = self.term_fc3(term_out_TYPE_C) - term_pred_TYPE_C = self.term_sigmoid(term_out_TYPE_C) - gaussian_TYPE_C = gaussian_2d(word_level_target_x, word_level_target_y, mu1_TYPE_C, mu2_TYPE_C, sig1_TYPE_C, sig2_TYPE_C, rho_TYPE_C) - loss_gaussian_TYPE_C = - torch.log(torch.sum(pi_TYPE_C*gaussian_TYPE_C, dim=1) + 1e-5) - - TYPE_C_word_term_loss = self.term_bce_loss(term_out_TYPE_C.squeeze(1), word_level_target_term) - TYPE_C_word_loc_loss = torch.mean(loss_gaussian_TYPE_C) - TYPE_C_word_touch_loss = self.mdn_bce_loss(eos_TYPE_C.squeeze(1), word_level_target_eos) - - TYPE_C_word_termination_loss.append(TYPE_C_word_term_loss) - TYPE_C_word_loc_reconstruct_loss.append(TYPE_C_word_loc_loss) - TYPE_C_word_touch_reconstruct_loss.append(TYPE_C_word_touch_loss) - else: - print ("not C") - - if self.TYPE_D: - word_Wc_rec_TYPE_D = [] - TYPE_D_REF = [] - for segment_batch_id in range(len(segment_Wc_rec_ORIGINAL)): - if segment_batch_id == 0: - for each_segment_Wc in segment_Wc_rec_ORIGINAL[segment_batch_id]: - word_Wc_rec_TYPE_D.append(each_segment_Wc) - TYPE_D_REF.append(segment_Wc_rec_ORIGINAL[segment_batch_id][-1]) - else: - for each_segment_Wc in segment_Wc_rec_ORIGINAL[segment_batch_id]: - magic_inp = torch.cat([torch.stack(TYPE_D_REF, 0), each_segment_Wc.unsqueeze(0)], 0) - magic_inp = magic_inp.unsqueeze(0) - TYPE_D_out, (c,h) = self.magic_lstm(magic_inp) - TYPE_D_out = TYPE_D_out.squeeze(0) - word_Wc_rec_TYPE_D.append(TYPE_D_out[-1]) - TYPE_D_REF.append(segment_Wc_rec_ORIGINAL[segment_batch_id][-1]) - word_Wc_rec_TYPE_D = torch.stack(word_Wc_rec_TYPE_D) - word_Wcs_reconstruct_TYPE_D.append(word_Wc_rec_TYPE_D) - - if len(word_Wc_rec_TYPE_D) == len(word_SPLITS[word_batch_id]): - word_W_lstm_in_TYPE_D = [] - curr_id = 0 - for i in range(user_word_level_stroke_length[word_batch_id][0]): - word_W_lstm_in_TYPE_D.append(word_Wc_rec_TYPE_D[curr_id]) - if i in word_SPLITS[word_batch_id]: - curr_id += 1 - word_Wc_t_rec_TYPE_D = torch.stack(word_W_lstm_in_TYPE_D) - - word_gen_lstm2_in_TYPE_D = torch.cat([word_level_gen_encoded, word_Wc_t_rec_TYPE_D], -1) - word_gen_lstm2_in_TYPE_D = word_gen_lstm2_in_TYPE_D.unsqueeze(0) - word_gen_out_TYPE_D, (c,h) = self.gen_state_lstm2(word_gen_lstm2_in_TYPE_D) - word_gen_out_TYPE_D = word_gen_out_TYPE_D.squeeze(0) - - mdn_out_TYPE_D = self.gen_state_fc2(word_gen_out_TYPE_D) - eos_TYPE_D = mdn_out_TYPE_D[:,0:1] - [mu1_TYPE_D, mu2_TYPE_D, sig1_TYPE_D, sig2_TYPE_D, rho_TYPE_D, pi_TYPE_D] = torch.split(mdn_out_TYPE_D[:,1:], self.num_mixtures, 1) - sig1_TYPE_D = sig1_TYPE_D.exp() + 1e-3 - sig2_TYPE_D = sig2_TYPE_D.exp() + 1e-3 - rho_TYPE_D = self.mdn_tanh(rho_TYPE_D) - pi_TYPE_D = self.mdn_softmax(pi_TYPE_D) - term_out_TYPE_D = self.term_fc1(word_gen_out_TYPE_D) - term_out_TYPE_D = self.term_relu1(term_out_TYPE_D) - term_out_TYPE_D = self.term_fc2(term_out_TYPE_D) - term_out_TYPE_D = self.term_relu2(term_out_TYPE_D) - term_out_TYPE_D = self.term_fc3(term_out_TYPE_D) - term_pred_TYPE_D = self.term_sigmoid(term_out_TYPE_D) - gaussian_TYPE_D = gaussian_2d(word_level_target_x, word_level_target_y, mu1_TYPE_D, mu2_TYPE_D, sig1_TYPE_D, sig2_TYPE_D, rho_TYPE_D) - loss_gaussian_TYPE_D = - torch.log(torch.sum(pi_TYPE_D*gaussian_TYPE_D, dim=1) + 1e-5) - - TYPE_D_word_term_loss = self.term_bce_loss(term_out_TYPE_D.squeeze(1), word_level_target_term) - TYPE_D_word_loc_loss = torch.mean(loss_gaussian_TYPE_D) - TYPE_D_word_touch_loss = self.mdn_bce_loss(eos_TYPE_D.squeeze(1), word_level_target_eos) - - TYPE_D_word_termination_loss.append(TYPE_D_word_term_loss) - TYPE_D_word_loc_reconstruct_loss.append(TYPE_D_word_loc_loss) - TYPE_D_word_touch_reconstruct_loss.append(TYPE_D_word_touch_loss) - else: - print ("not D") - - # word - if self.ORIGINAL: - ALL_ORIGINAL_word_termination_loss.append(torch.mean(torch.stack(ORIGINAL_word_termination_loss))) - ALL_ORIGINAL_word_loc_reconstruct_loss.append(torch.mean(torch.stack(ORIGINAL_word_loc_reconstruct_loss))) - ALL_ORIGINAL_word_touch_reconstruct_loss.append(torch.mean(torch.stack(ORIGINAL_word_touch_reconstruct_loss))) - - if self.TYPE_A: - ALL_TYPE_A_word_termination_loss.append(torch.mean(torch.stack(TYPE_A_word_termination_loss))) - ALL_TYPE_A_word_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_word_loc_reconstruct_loss))) - ALL_TYPE_A_word_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_word_touch_reconstruct_loss))) - - if self.REC: - TYPE_A_word_WC_reconstruct_loss = [] - for word_batch_id in range(len(word_Wc_rec_ORIGINAL)): - word_Wc_ORIGINAL = word_Wc_rec_ORIGINAL[word_batch_id] - word_Wc_TYPE_A = word_Wcs_reconstruct_TYPE_A[word_batch_id] - if len(word_Wc_ORIGINAL) == len(word_Wc_TYPE_A): - word_WC_reconstruct_loss_TYPE_A = torch.mean(torch.mean(torch.mul(word_Wc_ORIGINAL - word_Wc_TYPE_A, word_Wc_ORIGINAL - word_Wc_TYPE_A), -1)) - TYPE_A_word_WC_reconstruct_loss.append(word_WC_reconstruct_loss_TYPE_A) - if len(TYPE_A_word_WC_reconstruct_loss) > 0: - ALL_TYPE_A_word_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_A_word_WC_reconstruct_loss))) - - if self.TYPE_B: - ALL_TYPE_B_word_termination_loss.append(torch.mean(torch.stack(TYPE_B_word_termination_loss))) - ALL_TYPE_B_word_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_word_loc_reconstruct_loss))) - ALL_TYPE_B_word_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_word_touch_reconstruct_loss))) - - if self.REC: - TYPE_B_word_WC_reconstruct_loss = [] - for word_batch_id in range(len(word_Wc_rec_ORIGINAL)): - word_Wc_ORIGINAL = word_Wc_rec_ORIGINAL[word_batch_id] - word_Wc_TYPE_B = word_Wcs_reconstruct_TYPE_B[word_batch_id] - if len(word_Wc_ORIGINAL) == len(word_Wc_TYPE_B): - word_WC_reconstruct_loss_TYPE_B = torch.mean(torch.mean(torch.mul(word_Wc_ORIGINAL - word_Wc_TYPE_B, word_Wc_ORIGINAL - word_Wc_TYPE_B), -1)) - TYPE_B_word_WC_reconstruct_loss.append(word_WC_reconstruct_loss_TYPE_B) - if len(TYPE_B_word_WC_reconstruct_loss) > 0: - ALL_TYPE_B_word_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_B_word_WC_reconstruct_loss))) - - if self.TYPE_C: - ALL_TYPE_C_word_termination_loss.append(torch.mean(torch.stack(TYPE_C_word_termination_loss))) - ALL_TYPE_C_word_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_C_word_loc_reconstruct_loss))) - ALL_TYPE_C_word_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_C_word_touch_reconstruct_loss))) - - if self.REC: - TYPE_C_word_WC_reconstruct_loss = [] - for word_batch_id in range(len(word_Wc_rec_ORIGINAL)): - word_Wc_ORIGINAL = word_Wc_rec_ORIGINAL[word_batch_id] - word_Wc_TYPE_C = word_Wcs_reconstruct_TYPE_C[word_batch_id] - if len(word_Wc_ORIGINAL) == len(word_Wc_TYPE_C): - word_WC_reconstruct_loss_TYPE_C = torch.mean(torch.mean(torch.mul(word_Wc_ORIGINAL - word_Wc_TYPE_C, word_Wc_ORIGINAL - word_Wc_TYPE_C), -1)) - TYPE_C_word_WC_reconstruct_loss.append(word_WC_reconstruct_loss_TYPE_C) - if len(TYPE_C_word_WC_reconstruct_loss) > 0: - ALL_TYPE_C_word_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_C_word_WC_reconstruct_loss))) - - if self.TYPE_D: - ALL_TYPE_D_word_termination_loss.append(torch.mean(torch.stack(TYPE_D_word_termination_loss))) - ALL_TYPE_D_word_loc_reconstruct_loss.append(torch.mean(torch.stack(TYPE_D_word_loc_reconstruct_loss))) - ALL_TYPE_D_word_touch_reconstruct_loss.append(torch.mean(torch.stack(TYPE_D_word_touch_reconstruct_loss))) - - if self.REC: - TYPE_D_word_WC_reconstruct_loss = [] - for word_batch_id in range(len(word_Wc_rec_ORIGINAL)): - word_Wc_ORIGINAL = word_Wc_rec_ORIGINAL[word_batch_id] - word_Wc_TYPE_D = word_Wcs_reconstruct_TYPE_D[word_batch_id] - if len(word_Wc_ORIGINAL) == len(word_Wc_TYPE_D): - word_WC_reconstruct_loss_TYPE_D = torch.mean(torch.mean(torch.mul(word_Wc_ORIGINAL - word_Wc_TYPE_D, word_Wc_ORIGINAL - word_Wc_TYPE_D), -1)) - TYPE_D_word_WC_reconstruct_loss.append(word_WC_reconstruct_loss_TYPE_D) - if len(TYPE_D_word_WC_reconstruct_loss) > 0: - ALL_TYPE_D_word_WC_reconstruct_loss.append(torch.mean(torch.stack(TYPE_D_word_WC_reconstruct_loss))) - - # segment - if self.segment_loss: - SUPER_ALL_segment_W_consistency_loss.append(torch.mean(torch.stack(ALL_segment_W_consistency_loss))) - - if self.ORIGINAL: - SUPER_ALL_ORIGINAL_segment_termination_loss.append(torch.mean(torch.stack(ALL_ORIGINAL_segment_termination_loss))) - SUPER_ALL_ORIGINAL_segment_loc_reconstruct_loss.append(torch.mean(torch.stack(ALL_ORIGINAL_segment_loc_reconstruct_loss))) - SUPER_ALL_ORIGINAL_segment_touch_reconstruct_loss.append(torch.mean(torch.stack(ALL_ORIGINAL_segment_touch_reconstruct_loss))) - - if self.TYPE_A: - SUPER_ALL_TYPE_A_segment_termination_loss.append(torch.mean(torch.stack(ALL_TYPE_A_segment_termination_loss))) - SUPER_ALL_TYPE_A_segment_loc_reconstruct_loss.append(torch.mean(torch.stack(ALL_TYPE_A_segment_loc_reconstruct_loss))) - SUPER_ALL_TYPE_A_segment_touch_reconstruct_loss.append(torch.mean(torch.stack(ALL_TYPE_A_segment_touch_reconstruct_loss))) - if self.REC: - SUPER_ALL_TYPE_A_segment_WC_reconstruct_loss.append(torch.mean(torch.stack(ALL_TYPE_A_segment_WC_reconstruct_loss))) - - if self.TYPE_B: - SUPER_ALL_TYPE_B_segment_termination_loss.append(torch.mean(torch.stack(ALL_TYPE_B_segment_termination_loss))) - SUPER_ALL_TYPE_B_segment_loc_reconstruct_loss.append(torch.mean(torch.stack(ALL_TYPE_B_segment_loc_reconstruct_loss))) - SUPER_ALL_TYPE_B_segment_touch_reconstruct_loss.append(torch.mean(torch.stack(ALL_TYPE_B_segment_touch_reconstruct_loss))) - if self.REC: - SUPER_ALL_TYPE_B_segment_WC_reconstruct_loss.append(torch.mean(torch.stack(ALL_TYPE_B_segment_WC_reconstruct_loss))) - - total_sentence_loss = 0 - sentence_losses = [] - if self.sentence_loss: - mean_ORIGINAL_sentence_termination_loss = 0 - mean_ORIGINAL_sentence_loc_reconstruct_loss = 0 - mean_ORIGINAL_sentence_touch_reconstruct_loss = 0 - mean_TYPE_A_sentence_termination_loss = 0 - mean_TYPE_A_sentence_loc_reconstruct_loss = 0 - mean_TYPE_A_sentence_touch_reconstruct_loss = 0 - mean_TYPE_B_sentence_termination_loss = 0 - mean_TYPE_B_sentence_loc_reconstruct_loss = 0 - mean_TYPE_B_sentence_touch_reconstruct_loss = 0 - mean_TYPE_A_sentence_WC_reconstruct_loss = 0 - mean_TYPE_B_sentence_WC_reconstruct_loss = 0 - - mean_sentence_W_consistency_loss = torch.mean(torch.stack(ALL_sentence_W_consistency_loss)) - if self.ORIGINAL: - mean_ORIGINAL_sentence_termination_loss = torch.mean(torch.stack(ALL_ORIGINAL_sentence_termination_loss)) - mean_ORIGINAL_sentence_loc_reconstruct_loss = torch.mean(torch.stack(ALL_ORIGINAL_sentence_loc_reconstruct_loss)) - mean_ORIGINAL_sentence_touch_reconstruct_loss = torch.mean(torch.stack(ALL_ORIGINAL_sentence_touch_reconstruct_loss)) - if self.TYPE_A: - mean_TYPE_A_sentence_termination_loss = torch.mean(torch.stack(ALL_TYPE_A_sentence_termination_loss)) - mean_TYPE_A_sentence_loc_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_A_sentence_loc_reconstruct_loss)) - mean_TYPE_A_sentence_touch_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_A_sentence_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_A_sentence_WC_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_A_sentence_WC_reconstruct_loss)) - if self.TYPE_B: - mean_TYPE_B_sentence_termination_loss = torch.mean(torch.stack(ALL_TYPE_B_sentence_termination_loss)) - mean_TYPE_B_sentence_loc_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_B_sentence_loc_reconstruct_loss)) - mean_TYPE_B_sentence_touch_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_B_sentence_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_B_sentence_WC_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_B_sentence_WC_reconstruct_loss)) - - total_sentence_loss = mean_sentence_W_consistency_loss + mean_ORIGINAL_sentence_termination_loss + mean_ORIGINAL_sentence_loc_reconstruct_loss + mean_ORIGINAL_sentence_touch_reconstruct_loss + mean_TYPE_A_sentence_termination_loss + mean_TYPE_A_sentence_loc_reconstruct_loss + mean_TYPE_A_sentence_touch_reconstruct_loss + mean_TYPE_B_sentence_termination_loss + mean_TYPE_B_sentence_loc_reconstruct_loss + mean_TYPE_B_sentence_touch_reconstruct_loss + mean_TYPE_A_sentence_WC_reconstruct_loss + mean_TYPE_B_sentence_WC_reconstruct_loss - sentence_losses = [total_sentence_loss, mean_sentence_W_consistency_loss, mean_ORIGINAL_sentence_termination_loss, mean_ORIGINAL_sentence_loc_reconstruct_loss, mean_ORIGINAL_sentence_touch_reconstruct_loss, mean_TYPE_A_sentence_termination_loss, mean_TYPE_A_sentence_loc_reconstruct_loss, mean_TYPE_A_sentence_touch_reconstruct_loss, mean_TYPE_B_sentence_termination_loss, mean_TYPE_B_sentence_loc_reconstruct_loss, mean_TYPE_B_sentence_touch_reconstruct_loss, mean_TYPE_A_sentence_WC_reconstruct_loss, mean_TYPE_B_sentence_WC_reconstruct_loss] - - total_word_loss = 0 - word_losses = [] - if self.word_loss: - mean_ORIGINAL_word_termination_loss = 0 - mean_ORIGINAL_word_loc_reconstruct_loss = 0 - mean_ORIGINAL_word_touch_reconstruct_loss = 0 - mean_TYPE_A_word_termination_loss = 0 - mean_TYPE_A_word_loc_reconstruct_loss = 0 - mean_TYPE_A_word_touch_reconstruct_loss = 0 - mean_TYPE_B_word_termination_loss = 0 - mean_TYPE_B_word_loc_reconstruct_loss = 0 - mean_TYPE_B_word_touch_reconstruct_loss = 0 - mean_TYPE_C_word_termination_loss = 0 - mean_TYPE_C_word_loc_reconstruct_loss = 0 - mean_TYPE_C_word_touch_reconstruct_loss = 0 - mean_TYPE_D_word_termination_loss = 0 - mean_TYPE_D_word_loc_reconstruct_loss = 0 - mean_TYPE_D_word_touch_reconstruct_loss = 0 - mean_TYPE_A_word_WC_reconstruct_loss = 0 - mean_TYPE_B_word_WC_reconstruct_loss = 0 - mean_TYPE_C_word_WC_reconstruct_loss = 0 - mean_TYPE_D_word_WC_reconstruct_loss = 0 - - mean_word_W_consistency_loss = torch.mean(torch.stack(ALL_word_W_consistency_loss)) - if self.ORIGINAL: - mean_ORIGINAL_word_termination_loss = torch.mean(torch.stack(ALL_ORIGINAL_word_termination_loss)) - mean_ORIGINAL_word_loc_reconstruct_loss = torch.mean(torch.stack(ALL_ORIGINAL_word_loc_reconstruct_loss)) - mean_ORIGINAL_word_touch_reconstruct_loss = torch.mean(torch.stack(ALL_ORIGINAL_word_touch_reconstruct_loss)) - if self.TYPE_A: - mean_TYPE_A_word_termination_loss = torch.mean(torch.stack(ALL_TYPE_A_word_termination_loss)) - mean_TYPE_A_word_loc_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_A_word_loc_reconstruct_loss)) - mean_TYPE_A_word_touch_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_A_word_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_A_word_WC_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_A_word_WC_reconstruct_loss)) - if self.TYPE_B: - mean_TYPE_B_word_termination_loss = torch.mean(torch.stack(ALL_TYPE_B_word_termination_loss)) - mean_TYPE_B_word_loc_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_B_word_loc_reconstruct_loss)) - mean_TYPE_B_word_touch_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_B_word_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_B_word_WC_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_B_word_WC_reconstruct_loss)) - if self.TYPE_C: - mean_TYPE_C_word_termination_loss = torch.mean(torch.stack(ALL_TYPE_C_word_termination_loss)) - mean_TYPE_C_word_loc_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_C_word_loc_reconstruct_loss)) - mean_TYPE_C_word_touch_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_C_word_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_C_word_WC_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_C_word_WC_reconstruct_loss)) - if self.TYPE_D: - mean_TYPE_D_word_termination_loss = torch.mean(torch.stack(ALL_TYPE_D_word_termination_loss)) - mean_TYPE_D_word_loc_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_D_word_loc_reconstruct_loss)) - mean_TYPE_D_word_touch_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_D_word_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_D_word_WC_reconstruct_loss = torch.mean(torch.stack(ALL_TYPE_D_word_WC_reconstruct_loss)) - - total_word_loss = mean_word_W_consistency_loss + mean_ORIGINAL_word_termination_loss + mean_ORIGINAL_word_loc_reconstruct_loss + mean_ORIGINAL_word_touch_reconstruct_loss + mean_TYPE_A_word_termination_loss + mean_TYPE_A_word_loc_reconstruct_loss + mean_TYPE_A_word_touch_reconstruct_loss + mean_TYPE_B_word_termination_loss + mean_TYPE_B_word_loc_reconstruct_loss + mean_TYPE_B_word_touch_reconstruct_loss + mean_TYPE_C_word_termination_loss + mean_TYPE_C_word_loc_reconstruct_loss + mean_TYPE_C_word_touch_reconstruct_loss + mean_TYPE_D_word_termination_loss + mean_TYPE_D_word_loc_reconstruct_loss + mean_TYPE_D_word_touch_reconstruct_loss + mean_TYPE_A_word_WC_reconstruct_loss + mean_TYPE_B_word_WC_reconstruct_loss + mean_TYPE_C_word_WC_reconstruct_loss + mean_TYPE_D_word_WC_reconstruct_loss - word_losses = [total_word_loss, mean_word_W_consistency_loss, mean_ORIGINAL_word_termination_loss, mean_ORIGINAL_word_loc_reconstruct_loss, mean_ORIGINAL_word_touch_reconstruct_loss, mean_TYPE_A_word_termination_loss, mean_TYPE_A_word_loc_reconstruct_loss, mean_TYPE_A_word_touch_reconstruct_loss, mean_TYPE_B_word_termination_loss, mean_TYPE_B_word_loc_reconstruct_loss, mean_TYPE_B_word_touch_reconstruct_loss, mean_TYPE_C_word_termination_loss, mean_TYPE_C_word_loc_reconstruct_loss, mean_TYPE_C_word_touch_reconstruct_loss, mean_TYPE_D_word_termination_loss, mean_TYPE_D_word_loc_reconstruct_loss, mean_TYPE_D_word_touch_reconstruct_loss, mean_TYPE_A_word_WC_reconstruct_loss, mean_TYPE_B_word_WC_reconstruct_loss, mean_TYPE_C_word_WC_reconstruct_loss, mean_TYPE_D_word_WC_reconstruct_loss] - - total_segment_loss = 0 - segment_losses = [] - if self.segment_loss: - mean_segment_W_consistency_loss = torch.mean(torch.stack(SUPER_ALL_segment_W_consistency_loss)) - - mean_ORIGINAL_segment_termination_loss = 0 - mean_ORIGINAL_segment_loc_reconstruct_loss = 0 - mean_ORIGINAL_segment_touch_reconstruct_loss = 0 - mean_TYPE_A_segment_termination_loss = 0 - mean_TYPE_A_segment_loc_reconstruct_loss = 0 - mean_TYPE_A_segment_touch_reconstruct_loss = 0 - mean_TYPE_B_segment_termination_loss = 0 - mean_TYPE_B_segment_loc_reconstruct_loss = 0 - mean_TYPE_B_segment_touch_reconstruct_loss = 0 - mean_TYPE_A_segment_WC_reconstruct_loss = 0 - mean_TYPE_B_segment_WC_reconstruct_loss = 0 - - if self.ORIGINAL: - mean_ORIGINAL_segment_termination_loss = torch.mean(torch.stack(SUPER_ALL_ORIGINAL_segment_termination_loss)) - mean_ORIGINAL_segment_loc_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_ORIGINAL_segment_loc_reconstruct_loss)) - mean_ORIGINAL_segment_touch_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_ORIGINAL_segment_touch_reconstruct_loss)) - if self.TYPE_A: - mean_TYPE_A_segment_termination_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_A_segment_termination_loss)) - mean_TYPE_A_segment_loc_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_A_segment_loc_reconstruct_loss)) - mean_TYPE_A_segment_touch_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_A_segment_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_A_segment_WC_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_A_segment_WC_reconstruct_loss)) - if self.TYPE_B: - mean_TYPE_B_segment_termination_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_B_segment_termination_loss)) - mean_TYPE_B_segment_loc_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_B_segment_loc_reconstruct_loss)) - mean_TYPE_B_segment_touch_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_B_segment_touch_reconstruct_loss)) - if self.REC: - mean_TYPE_B_segment_WC_reconstruct_loss = torch.mean(torch.stack(SUPER_ALL_TYPE_B_segment_WC_reconstruct_loss)) - - total_segment_loss = mean_segment_W_consistency_loss + mean_ORIGINAL_segment_termination_loss + mean_ORIGINAL_segment_loc_reconstruct_loss + mean_ORIGINAL_segment_touch_reconstruct_loss + mean_TYPE_A_segment_termination_loss + mean_TYPE_A_segment_loc_reconstruct_loss + mean_TYPE_A_segment_touch_reconstruct_loss + mean_TYPE_B_segment_termination_loss + mean_TYPE_B_segment_loc_reconstruct_loss + mean_TYPE_B_segment_touch_reconstruct_loss + mean_TYPE_A_segment_WC_reconstruct_loss + mean_TYPE_B_segment_WC_reconstruct_loss - segment_losses = [total_segment_loss, mean_segment_W_consistency_loss, mean_ORIGINAL_segment_termination_loss, mean_ORIGINAL_segment_loc_reconstruct_loss, mean_ORIGINAL_segment_touch_reconstruct_loss, mean_TYPE_A_segment_termination_loss, mean_TYPE_A_segment_loc_reconstruct_loss, mean_TYPE_A_segment_touch_reconstruct_loss, mean_TYPE_B_segment_termination_loss, mean_TYPE_B_segment_loc_reconstruct_loss, mean_TYPE_B_segment_touch_reconstruct_loss, mean_TYPE_A_segment_WC_reconstruct_loss, mean_TYPE_B_segment_WC_reconstruct_loss] - - total_loss = total_sentence_loss + total_word_loss + total_segment_loss - - return total_loss, sentence_losses, word_losses, segment_losses - - def sample(self, inputs): - [ word_level_stroke_in, word_level_stroke_out, word_level_stroke_length, - word_level_term, word_level_char, word_level_char_length, segment_level_stroke_in, - segment_level_stroke_out, segment_level_stroke_length, segment_level_term, - segment_level_char, segment_level_char_length ] = inputs - - word_inf_state_out = self.inf_state_fc1(word_level_stroke_out[0]) - word_inf_state_out = self.inf_state_relu(word_inf_state_out) - word_inf_state_out, (c,h) = self.inf_state_lstm(word_inf_state_out) - - user_word_level_char = word_level_char[0] - user_word_level_term = word_level_term[0] - - raw_Ws = [] - original_Wc = [] - - word_batch_id = 0 - - # ORIGINAL - curr_seq_len = word_level_stroke_length[0][word_batch_id][0] - curr_char_len = word_level_char_length[0][word_batch_id][0] - - char_vector = torch.eye(len(CHARACTERS))[user_word_level_char[word_batch_id][:curr_char_len]].to(self.device) - current_term = user_word_level_term[word_batch_id][:curr_seq_len].unsqueeze(-1) - split_ids = torch.nonzero(current_term)[:,0] - - # char_vector = self.char_vec_fc(char_vector) - # char_vector = self.char_vec_relu(char_vector) - char_vector_1 = self.char_vec_fc_1(char_vector) - char_vector_1 = self.char_vec_relu_1(char_vector_1) - - # unique_char_matrices = [] - # for cid in range(len(char_vector)): - # unique_char_vector = char_vector[cid:cid+1] - # unique_char_out = unique_char_vector.unsqueeze(0) - # unique_char_out, (c,h) = self.char_lstm(unique_char_out) - # unique_char_out = unique_char_out.squeeze(0) - # unique_char_out = self.char_vec_fc2(unique_char_out) - # unique_char_matrix = unique_char_out.view([-1,1,self.weight_dim,self.weight_dim]) - # unique_char_matrix = unique_char_matrix.squeeze(1) - # unique_char_matrices.append(unique_char_matrix) - - unique_char_matrices_1 = [] - for cid in range(len(char_vector)): - # Tower 1 - unique_char_vector_1 = char_vector_1[cid:cid+1] - unique_char_input_1 = unique_char_vector_1.unsqueeze(0) - unique_char_out_1, (c,h) = self.char_lstm_1(unique_char_input_1) - unique_char_out_1 = unique_char_out_1.squeeze(0) - unique_char_out_1 = self.char_vec_fc2_1(unique_char_out_1) - unique_char_matrix_1 = unique_char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - unique_char_matrix_1 = unique_char_matrix_1.squeeze(1) - unique_char_matrices_1.append(unique_char_matrix_1) - - # Tower 1 - char_out_1 = char_vector_1.unsqueeze(0) - char_out_1, (c,h) = self.char_lstm_1(char_out_1) - char_out_1 = char_out_1.squeeze(0) - char_out_1 = self.char_vec_fc2_1(char_out_1) - char_matrix_1 = char_out_1.view([-1,1,self.weight_dim,self.weight_dim]) - char_matrix_1 = char_matrix_1.squeeze(1) - char_matrix_inv_1 = torch.inverse(char_matrix_1) - - W_c_t = word_inf_state_out[word_batch_id][:curr_seq_len] - W_c = torch.stack([W_c_t[i] for i in split_ids]) - original_Wc.append(W_c) - - W = torch.bmm(char_matrix_inv_1, - W_c.unsqueeze(2)).squeeze(-1) - - user_segment_level_stroke_length = segment_level_stroke_length[0][word_batch_id] - user_segment_level_char_length = segment_level_char_length[0][word_batch_id] - user_segment_level_term = segment_level_term[0][word_batch_id] - user_segment_level_char = segment_level_char[0][word_batch_id] - user_segment_level_stroke_in = segment_level_stroke_in[0][word_batch_id] - user_segment_level_stroke_out = segment_level_stroke_out[0][word_batch_id] - - segment_inf_state_out = self.inf_state_fc1(user_segment_level_stroke_out) - segment_inf_state_out = self.inf_state_relu(segment_inf_state_out) - segment_inf_state_out, (c,h) = self.inf_state_lstm(segment_inf_state_out) - - segment_W_c = [] - for segment_batch_id in range(len(user_segment_level_char)): - curr_seq_len = user_segment_level_stroke_length[segment_batch_id][0] - curr_char_len = user_segment_level_char_length[segment_batch_id][0] - current_term = user_segment_level_term[segment_batch_id][:curr_seq_len].unsqueeze(-1) - split_ids = torch.nonzero(current_term)[:,0] - - seg_W_c_t = segment_inf_state_out[segment_batch_id][:curr_seq_len] - seg_W_c = torch.stack([seg_W_c_t[i] for i in split_ids]) - segment_W_c.append(seg_W_c) - - target_characters_ids = word_level_char[0][0][:word_level_char_length[0][0]] - target_characters = ''.join([CHARACTERS[i] for i in target_characters_ids]) - - mean_global_W = torch.mean(W, 0) - - TYPE_A_WC = torch.bmm(char_matrix_1, - mean_global_W.repeat(char_matrix_1.size(0), 1).unsqueeze(2)).squeeze(-1) - - unique_char_matrix_1 = torch.stack(unique_char_matrices_1) - unique_char_matrix_1 = unique_char_matrix_1.squeeze(1) - - TYPE_B_WC_RAW = torch.bmm(unique_char_matrix_1, - mean_global_W.repeat(unique_char_matrix_1.size(0), 1).unsqueeze(2)).squeeze(-1) - - TYPE_B_WC_RAW = TYPE_B_WC_RAW.unsqueeze(0) - TYPE_B_WC, (c,h) = self.magic_lstm(TYPE_B_WC_RAW) - TYPE_B_WC = TYPE_B_WC.squeeze(0) - - # CC - TYPE_C_WC = [] - for segment_batch_id in range(len(segment_W_c)): - if segment_batch_id == 0: - for each_segment_Wc in segment_W_c[segment_batch_id]: - TYPE_C_WC.append(each_segment_Wc) - prev_id = len(TYPE_C_WC) - 1 - else: - prev_original_W_c = W_c[prev_id] - for each_segment_Wc in segment_W_c[segment_batch_id]: - magic_inp = torch.stack([prev_original_W_c, each_segment_Wc]) - magic_inp = magic_inp.unsqueeze(0) - type_c_out, (c,h) = self.magic_lstm(magic_inp) - type_c_out = type_c_out.squeeze(0) - TYPE_C_WC.append(type_c_out[-1]) - prev_id = len(TYPE_C_WC) - 1 - TYPE_C_WC = torch.stack(TYPE_C_WC) - - - # DD - TYPE_D_WC = [] - TYPE_D_REF = [] - for segment_batch_id in range(len(segment_W_c)): - if segment_batch_id == 0: - for each_segment_Wc in segment_W_c[segment_batch_id]: - TYPE_D_WC.append(each_segment_Wc) - TYPE_D_REF.append(segment_W_c[segment_batch_id][-1]) - else: - for each_segment_Wc in segment_W_c[segment_batch_id]: - magic_inp = torch.cat([torch.stack(TYPE_D_REF, 0), each_segment_Wc.unsqueeze(0)], 0) - magic_inp = magic_inp.unsqueeze(0) - TYPE_D_out, (c,h) = self.magic_lstm(magic_inp) - TYPE_D_out = TYPE_D_out.squeeze(0) - TYPE_D_WC.append(TYPE_D_out[-1]) - TYPE_D_REF.append(segment_W_c[segment_batch_id][-1]) - TYPE_D_WC = torch.stack(TYPE_D_WC) - - - o_tc = ''.join([CHARACTERS[c] for c in word_level_char[0][0][:word_level_char_length[0][0]]]) - o_commands = self.sample_from_w(original_Wc[0], o_tc) - if len(TYPE_A_WC) == len(original_Wc[0]): - a_commands = self.sample_from_w(TYPE_A_WC, target_characters) - else: - a_commands = [[0,0,0]] - - if len(TYPE_B_WC) == len(original_Wc[0]): - b_commands = self.sample_from_w(TYPE_B_WC, target_characters) - else: - b_commands = [[0,0,0]] - - if len(TYPE_C_WC) == len(original_Wc[0]): - c_commands = self.sample_from_w(TYPE_C_WC, target_characters) - else: - c_commands = [[0,0,0]] - - if len(TYPE_D_WC) == len(original_Wc[0]): - d_commands = self.sample_from_w(TYPE_D_WC, target_characters) - else: - d_commands = [[0,0,0]] - - return [word_level_stroke_out[0][0], o_commands, a_commands, b_commands, c_commands, d_commands] - - def sample_from_w(self, W_c_rec, target_sentence): - gen_input = torch.zeros([1, 1, 3]).to(self.device) - current_char_id_count = 0 - - gc1 = torch.zeros([self.num_layers, 1, self.weight_dim]).to(self.device) - gh1 = torch.zeros([self.num_layers, 1, self.weight_dim]).to(self.device) - gc2 = torch.zeros([self.num_layers, 1, self.weight_dim * 2]).to(self.device) - gh2 = torch.zeros([self.num_layers, 1, self.weight_dim * 2]).to(self.device) - - terms = [] - commands = [] - character_nums = 0 - cx, cy = 100, 150 - for zz in range(800): - W_c_t_now = W_c_rec[current_char_id_count:current_char_id_count + 1] - - gen_state = self.gen_state_fc1(gen_input) - gen_state = self.gen_state_relu(gen_state) - gen_state, (gc1, gh1) = self.gen_state_lstm1(gen_state, (gc1, gh1)) - gen_encoded = gen_state.squeeze(0) - - gen_lstm2_input = torch.cat([gen_encoded, W_c_t_now], -1) - gen_lstm2_input = gen_lstm2_input.view([1, 1, self.weight_dim * 2]) - gen_out, (gc2, gh2) = self.gen_state_lstm2(gen_lstm2_input, (gc2, gh2)) - gen_out = gen_out.squeeze(0) - mdn_out = self.gen_state_fc2(gen_out) - - term_out = self.term_fc1(gen_out) - term_out = self.term_relu1(term_out) - term_out = self.term_fc2(term_out) - term_out = self.term_relu2(term_out) - term_out = self.term_fc3(term_out) - term = self.term_sigmoid(term_out) - - eos = self.mdn_sigmoid(mdn_out[:, 0]) - [mu1, mu2, sig1, sig2, rho, pi] = torch.split(mdn_out[:, 1:], self.num_mixtures, 1) - sig1 = sig1.exp() + 1e-3 - sig2 = sig2.exp() + 1e-3 - rho = self.mdn_tanh(rho) - pi = self.mdn_softmax(pi) - mus = torch.stack([mu1, mu2], -1).squeeze() - - pi = pi.cpu().detach().numpy() - mus = mus.cpu().detach().numpy() - rho = rho.cpu().detach().numpy()[0] - eos = eos.cpu().detach().numpy()[0] - term = term.cpu().detach().numpy()[0][0] - - terms.append(term) - [dx, dy] = np.sum(pi.reshape(20, 1) * mus, 0) - # print (eos) - touch = 1 if eos > 0.5 else 0 - - commands.append([dx, dy, touch]) - gen_input = torch.FloatTensor([dx, dy, touch]).view([1, 1, 3]).to(self.device) - character_nums += 1 - - # print (zz, term) - if term > 0.3: - if target_sentence[current_char_id_count] == ' ': - current_char_id_count += 1 - character_nums = 0 - if current_char_id_count == len(W_c_rec): - break - elif character_nums > 5: - current_char_id_count += 1 - character_nums = 0 - if current_char_id_count == len(W_c_rec): - break - - cx += dx * 2.0 * 5.0 - cy += dy * 2.0 * 5.0 - if cx > 1000 or cx < 0: - break - if cy > 350 or cy < 0: - break - - return commands - - - def sample_from_w_fix(self, W_c_rec): - gen_input = torch.zeros([1, 1, 3]).to(self.device) - current_char_id_count = 0 - - gc1 = torch.zeros([self.num_layers, 1, self.weight_dim]).to(self.device) - gh1 = torch.zeros([self.num_layers, 1, self.weight_dim]).to(self.device) - gc2 = torch.zeros([self.num_layers, 1, self.weight_dim * 2]).to(self.device) - gh2 = torch.zeros([self.num_layers, 1, self.weight_dim * 2]).to(self.device) - - terms = [] - commands = [] - character_nums = 0 - cx, cy = 100, 150 - new_char = False - renewal = False - for zz in range(800): - # print (torch.sum(gc1)) - W_c_t_now = W_c_rec[current_char_id_count:current_char_id_count + 1] - - gen_state = self.gen_state_fc1(gen_input) - gen_state = self.gen_state_relu(gen_state) - gen_state, (gc1, gh1) = self.gen_state_lstm1(gen_state, (gc1, gh1)) - gen_encoded = gen_state.squeeze(0) - - gen_lstm2_input = torch.cat([gen_encoded, W_c_t_now], -1) - gen_lstm2_input = gen_lstm2_input.view([1, 1, self.weight_dim * 2]) - gen_out, (gc2, gh2) = self.gen_state_lstm2(gen_lstm2_input, (gc2, gh2)) - gen_out = gen_out.squeeze(0) - mdn_out = self.gen_state_fc2(gen_out) - - term_out = self.term_fc1(gen_out) - term_out = self.term_relu1(term_out) - term_out = self.term_fc2(term_out) - term_out = self.term_relu2(term_out) - term_out = self.term_fc3(term_out) - term = self.term_sigmoid(term_out) - - eos = self.mdn_sigmoid(mdn_out[:, 0]) - [mu1, mu2, sig1, sig2, rho, pi] = torch.split(mdn_out[:, 1:], self.num_mixtures, 1) - sig1 = sig1.exp() + 1e-3 - sig2 = sig2.exp() + 1e-3 - rho = self.mdn_tanh(rho) - pi = self.mdn_softmax(pi) - - mus = torch.stack([mu1, mu2], -1).squeeze() - sigs = torch.stack([sig1, sig2], -1).squeeze() * self.scale_sd - - distribution = torch.distributions.normal.Normal(loc=mus, scale=sigs) - sample = distribution.sample() - - min_clamp = distribution.icdf(0.5 - torch.ones_like(mus) * self.clamp_mdn/2) - max_clamp = distribution.icdf(0.5 + torch.ones_like(mus) * self.clamp_mdn/2) - - sample = sample.clamp(min=min_clamp, max=max_clamp) - - pi = pi.cpu().detach().numpy() - mus = mus.cpu().detach().numpy() - rho = rho.cpu().detach().numpy()[0] - eos = eos.cpu().detach().numpy()[0] - term = term.cpu().detach().numpy()[0][0] - - sample = sample.cpu().detach().numpy() - - terms.append(term) - [dx, dy] = np.sum(pi.reshape(20, 1) * sample, 0) - touch = 1 if eos > 0.5 else 0 - - if new_char and touch == 1: - new_char = False - commands.append([dx, dy, touch]) - return commands, current_char_id_count - else: - commands.append([dx, dy, touch]) - gen_input = torch.FloatTensor([dx, dy, touch]).view([1, 1, 3]).to(self.device) - - character_nums += 1 - - # print (zz, term) - if term > 0.5: - if character_nums > 5: - current_char_id_count += 1 - character_nums = 0 - new_char = True - if current_char_id_count == len(W_c_rec): - break - - cx += dx * 2.0 * 5.0 - cy += dy * 2.0 * 5.0 - if cx > 1000 or cx < 0: - break - if cy > 350 or cy < 0: - break - - return commands, -1 \ No newline at end of file diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/config/__init__.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/config/__init__.py deleted file mode 100644 index 4e648e632d55c70f160d49630378d202fbde4e45..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/config/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from .compat import downgrade_config, upgrade_config -from .config import CfgNode, get_cfg, global_cfg, set_global_cfg, configurable -from .instantiate import instantiate -from .lazy import LazyCall, LazyConfig - -__all__ = [ - "CfgNode", - "get_cfg", - "global_cfg", - "set_global_cfg", - "downgrade_config", - "upgrade_config", - "configurable", - "instantiate", - "LazyCall", - "LazyConfig", -] - - -from detectron2.utils.env import fixup_module_metadata - -fixup_module_metadata(__name__, globals(), __all__) -del fixup_module_metadata diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/structures/image_list.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/structures/image_list.py deleted file mode 100644 index f78cae77753dd13d450ecdb57dcb0649f1a5b8da..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/structures/image_list.py +++ /dev/null @@ -1,129 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from __future__ import division -from typing import Any, Dict, List, Optional, Tuple -import torch -from torch import device -from torch.nn import functional as F - -from detectron2.layers.wrappers import move_device_like, shapes_to_tensor - - -class ImageList(object): - """ - Structure that holds a list of images (of possibly - varying sizes) as a single tensor. - This works by padding the images to the same size. - The original sizes of each image is stored in `image_sizes`. - - Attributes: - image_sizes (list[tuple[int, int]]): each tuple is (h, w). - During tracing, it becomes list[Tensor] instead. - """ - - def __init__(self, tensor: torch.Tensor, image_sizes: List[Tuple[int, int]]): - """ - Arguments: - tensor (Tensor): of shape (N, H, W) or (N, C_1, ..., C_K, H, W) where K >= 1 - image_sizes (list[tuple[int, int]]): Each tuple is (h, w). It can - be smaller than (H, W) due to padding. - """ - self.tensor = tensor - self.image_sizes = image_sizes - - def __len__(self) -> int: - return len(self.image_sizes) - - def __getitem__(self, idx) -> torch.Tensor: - """ - Access the individual image in its original size. - - Args: - idx: int or slice - - Returns: - Tensor: an image of shape (H, W) or (C_1, ..., C_K, H, W) where K >= 1 - """ - size = self.image_sizes[idx] - return self.tensor[idx, ..., : size[0], : size[1]] - - @torch.jit.unused - def to(self, *args: Any, **kwargs: Any) -> "ImageList": - cast_tensor = self.tensor.to(*args, **kwargs) - return ImageList(cast_tensor, self.image_sizes) - - @property - def device(self) -> device: - return self.tensor.device - - @staticmethod - def from_tensors( - tensors: List[torch.Tensor], - size_divisibility: int = 0, - pad_value: float = 0.0, - padding_constraints: Optional[Dict[str, int]] = None, - ) -> "ImageList": - """ - Args: - tensors: a tuple or list of `torch.Tensor`, each of shape (Hi, Wi) or - (C_1, ..., C_K, Hi, Wi) where K >= 1. The Tensors will be padded - to the same shape with `pad_value`. - size_divisibility (int): If `size_divisibility > 0`, add padding to ensure - the common height and width is divisible by `size_divisibility`. - This depends on the model and many models need a divisibility of 32. - pad_value (float): value to pad. - padding_constraints (optional[Dict]): If given, it would follow the format as - {"size_divisibility": int, "square_size": int}, where `size_divisibility` will - overwrite the above one if presented and `square_size` indicates the - square padding size if `square_size` > 0. - Returns: - an `ImageList`. - """ - assert len(tensors) > 0 - assert isinstance(tensors, (tuple, list)) - for t in tensors: - assert isinstance(t, torch.Tensor), type(t) - assert t.shape[:-2] == tensors[0].shape[:-2], t.shape - - image_sizes = [(im.shape[-2], im.shape[-1]) for im in tensors] - image_sizes_tensor = [shapes_to_tensor(x) for x in image_sizes] - max_size = torch.stack(image_sizes_tensor).max(0).values - - if padding_constraints is not None: - square_size = padding_constraints.get("square_size", 0) - if square_size > 0: - # pad to square. - max_size[0] = max_size[1] = square_size - if "size_divisibility" in padding_constraints: - size_divisibility = padding_constraints["size_divisibility"] - if size_divisibility > 1: - stride = size_divisibility - # the last two dims are H,W, both subject to divisibility requirement - max_size = (max_size + (stride - 1)).div(stride, rounding_mode="floor") * stride - - # handle weirdness of scripting and tracing ... - if torch.jit.is_scripting(): - max_size: List[int] = max_size.to(dtype=torch.long).tolist() - else: - if torch.jit.is_tracing(): - image_sizes = image_sizes_tensor - - if len(tensors) == 1: - # This seems slightly (2%) faster. - # TODO: check whether it's faster for multiple images as well - image_size = image_sizes[0] - padding_size = [0, max_size[-1] - image_size[1], 0, max_size[-2] - image_size[0]] - batched_imgs = F.pad(tensors[0], padding_size, value=pad_value).unsqueeze_(0) - else: - # max_size can be a tensor in tracing mode, therefore convert to list - batch_shape = [len(tensors)] + list(tensors[0].shape[:-2]) + list(max_size) - device = ( - None if torch.jit.is_scripting() else ("cpu" if torch.jit.is_tracing() else None) - ) - batched_imgs = tensors[0].new_full(batch_shape, pad_value, device=device) - batched_imgs = move_device_like(batched_imgs, tensors[0]) - for i, img in enumerate(tensors): - # Use `batched_imgs` directly instead of `img, pad_img = zip(tensors, batched_imgs)` - # Tracing mode cannot capture `copy_()` of temporary locals - batched_imgs[i, ..., : img.shape[-2], : img.shape[-1]].copy_(img) - - return ImageList(batched_imgs.contiguous(), image_sizes) diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/MViTv2/configs/cascade_mask_rcnn_mvitv2_t_3x.py b/spaces/brjathu/HMR2.0/vendor/detectron2/projects/MViTv2/configs/cascade_mask_rcnn_mvitv2_t_3x.py deleted file mode 100644 index 51327dd9379b011c2d6cdc8299515b6df8112f4e..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/MViTv2/configs/cascade_mask_rcnn_mvitv2_t_3x.py +++ /dev/null @@ -1,48 +0,0 @@ -from detectron2.config import LazyCall as L -from detectron2.layers import ShapeSpec -from detectron2.modeling.box_regression import Box2BoxTransform -from detectron2.modeling.matcher import Matcher -from detectron2.modeling.roi_heads import FastRCNNOutputLayers, FastRCNNConvFCHead, CascadeROIHeads -from detectron2.layers.batch_norm import NaiveSyncBatchNorm - -from .mask_rcnn_mvitv2_t_3x import model, dataloader, optimizer, lr_multiplier, train - - -# arguments that don't exist for Cascade R-CNN -[model.roi_heads.pop(k) for k in ["box_head", "box_predictor", "proposal_matcher"]] - -model.roi_heads.update( - _target_=CascadeROIHeads, - box_heads=[ - L(FastRCNNConvFCHead)( - input_shape=ShapeSpec(channels=256, height=7, width=7), - conv_dims=[256, 256, 256, 256], - fc_dims=[1024], - conv_norm=lambda c: NaiveSyncBatchNorm(c, stats_mode="N"), - ) - for _ in range(3) - ], - box_predictors=[ - L(FastRCNNOutputLayers)( - input_shape=ShapeSpec(channels=1024), - test_score_thresh=0.05, - box2box_transform=L(Box2BoxTransform)(weights=(w1, w1, w2, w2)), - cls_agnostic_bbox_reg=True, - num_classes="${...num_classes}", - ) - for (w1, w2) in [(10, 5), (20, 10), (30, 15)] - ], - proposal_matchers=[ - L(Matcher)(thresholds=[th], labels=[0, 1], allow_low_quality_matches=False) - for th in [0.5, 0.6, 0.7] - ], -) - -# Using NaiveSyncBatchNorm becase heads may have empty input. That is not supported by -# torch.nn.SyncBatchNorm. We can remove this after -# https://github.com/pytorch/pytorch/issues/36530 is fixed. -model.roi_heads.mask_head.conv_norm = lambda c: NaiveSyncBatchNorm(c, stats_mode="N") - -# 2conv in RPN: -# https://github.com/tensorflow/tpu/blob/b24729de804fdb751b06467d3dce0637fa652060/models/official/detection/modeling/architecture/heads.py#L95-L97 # noqa: E501, B950 -model.proposal_generator.head.conv_dims = [-1, -1] diff --git a/spaces/cadige/03GR-Chatbot-Memory/README.md b/spaces/cadige/03GR-Chatbot-Memory/README.md deleted file mode 100644 index 0e59cb7ca03526e32f1ce54d1ed9f13ea6dcae41..0000000000000000000000000000000000000000 --- a/spaces/cadige/03GR-Chatbot-Memory/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 03GR Chatbot Memory -emoji: 🐨 -colorFrom: indigo -colorTo: pink -sdk: gradio -sdk_version: 3.6 -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/carlosalonso/Detection-video/carpeta_deteccion/projects/TensorMask/tensormask/__init__.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/TensorMask/tensormask/__init__.py deleted file mode 100644 index eec7978ac3c5204b1e51dac03ba3d45efc5b379d..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/TensorMask/tensormask/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from .config import add_tensormask_config -from .arch import TensorMask diff --git a/spaces/cbhasker/bhasker1323genAIApp/README.md b/spaces/cbhasker/bhasker1323genAIApp/README.md deleted file mode 100644 index ff5a9552a4271d727b88e873bf26328ef2e1136f..0000000000000000000000000000000000000000 --- a/spaces/cbhasker/bhasker1323genAIApp/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Bhasker1323genAIApp -emoji: 🏆 -colorFrom: gray -colorTo: yellow -sdk: gradio -sdk_version: 3.39.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/chendl/compositional_test/transformers/examples/research_projects/performer/full_script.sh b/spaces/chendl/compositional_test/transformers/examples/research_projects/performer/full_script.sh deleted file mode 100644 index 8634666f983bb5fd1db46590ea615082ddacd9b3..0000000000000000000000000000000000000000 --- a/spaces/chendl/compositional_test/transformers/examples/research_projects/performer/full_script.sh +++ /dev/null @@ -1 +0,0 @@ -TOKENIZERS_PARALLELISM=true python run_mlm_performer.py --output_dir experiments --dataset_name wikipedia --dataset_config_name 20200501.en --model_name_or_path bert-large-cased --tokenizer_name bert-large-cased --do_train --overwrite_output_dir --per_device_train_batch_size 4 --learning_rate 5e-4 --warmup_steps 100 --num_train_epochs 3 --performer \ No newline at end of file diff --git a/spaces/chiye/background-remover/README.md b/spaces/chiye/background-remover/README.md deleted file mode 100644 index 0bcc69015de8bd1e071c10e80bf3a6620da755c8..0000000000000000000000000000000000000000 --- a/spaces/chiye/background-remover/README.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Background Remover -emoji: 🖼️✂️ -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 2.9.4 -app_file: app.py -pinned: false -duplicated_from: nateraw/background-remover ---- - -# background-remover - -[![Generic badge](https://img.shields.io/badge/🤗-Open%20In%20Spaces-blue.svg)](https://huggingface.co/spaces/nateraw/background-remover) - -A Gradio app to remove the background from an image - ----⬇️ - -Autogenerated using [this template](https://github.com/nateraw/spaces-template) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/commontypes.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/commontypes.py deleted file mode 100644 index 8ec97c756a4b1023fd3963dd39b706f7c0e34373..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cffi/commontypes.py +++ /dev/null @@ -1,80 +0,0 @@ -import sys -from . import model -from .error import FFIError - - -COMMON_TYPES = {} - -try: - # fetch "bool" and all simple Windows types - from _cffi_backend import _get_common_types - _get_common_types(COMMON_TYPES) -except ImportError: - pass - -COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE') -COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above - -for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES: - if _type.endswith('_t'): - COMMON_TYPES[_type] = _type -del _type - -_CACHE = {} - -def resolve_common_type(parser, commontype): - try: - return _CACHE[commontype] - except KeyError: - cdecl = COMMON_TYPES.get(commontype, commontype) - if not isinstance(cdecl, str): - result, quals = cdecl, 0 # cdecl is already a BaseType - elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES: - result, quals = model.PrimitiveType(cdecl), 0 - elif cdecl == 'set-unicode-needed': - raise FFIError("The Windows type %r is only available after " - "you call ffi.set_unicode()" % (commontype,)) - else: - if commontype == cdecl: - raise FFIError( - "Unsupported type: %r. Please look at " - "http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations " - "and file an issue if you think this type should really " - "be supported." % (commontype,)) - result, quals = parser.parse_type_and_quals(cdecl) # recursive - - assert isinstance(result, model.BaseTypeByIdentity) - _CACHE[commontype] = result, quals - return result, quals - - -# ____________________________________________________________ -# extra types for Windows (most of them are in commontypes.c) - - -def win_common_types(): - return { - "UNICODE_STRING": model.StructType( - "_UNICODE_STRING", - ["Length", - "MaximumLength", - "Buffer"], - [model.PrimitiveType("unsigned short"), - model.PrimitiveType("unsigned short"), - model.PointerType(model.PrimitiveType("wchar_t"))], - [-1, -1, -1]), - "PUNICODE_STRING": "UNICODE_STRING *", - "PCUNICODE_STRING": "const UNICODE_STRING *", - - "TBYTE": "set-unicode-needed", - "TCHAR": "set-unicode-needed", - "LPCTSTR": "set-unicode-needed", - "PCTSTR": "set-unicode-needed", - "LPTSTR": "set-unicode-needed", - "PTSTR": "set-unicode-needed", - "PTBYTE": "set-unicode-needed", - "PTCHAR": "set-unicode-needed", - } - -if sys.platform == 'win32': - COMMON_TYPES.update(win_common_types()) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/enum/section.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/enum/section.py deleted file mode 100644 index 381e81877ac9b4d495b6c3bfc0707fb0ba17d55a..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/enum/section.py +++ /dev/null @@ -1,103 +0,0 @@ -# encoding: utf-8 - -""" -Enumerations related to the main document in WordprocessingML files -""" - -from __future__ import absolute_import, print_function, unicode_literals - -from .base import alias, XmlEnumeration, XmlMappedEnumMember - - -@alias('WD_HEADER_FOOTER') -class WD_HEADER_FOOTER_INDEX(XmlEnumeration): - """ - alias: **WD_HEADER_FOOTER** - - Specifies one of the three possible header/footer definitions for a section. - - For internal use only; not part of the python-docx API. - """ - - __ms_name__ = "WdHeaderFooterIndex" - - __url__ = "https://docs.microsoft.com/en-us/office/vba/api/word.wdheaderfooterindex" - - __members__ = ( - XmlMappedEnumMember( - "PRIMARY", 1, "default", "Header for odd pages or all if no even header." - ), - XmlMappedEnumMember( - "FIRST_PAGE", 2, "first", "Header for first page of section." - ), - XmlMappedEnumMember( - "EVEN_PAGE", 3, "even", "Header for even pages of recto/verso section." - ), - ) - - -@alias('WD_ORIENT') -class WD_ORIENTATION(XmlEnumeration): - """ - alias: **WD_ORIENT** - - Specifies the page layout orientation. - - Example:: - - from docx.enum.section import WD_ORIENT - - section = document.sections[-1] - section.orientation = WD_ORIENT.LANDSCAPE - """ - - __ms_name__ = 'WdOrientation' - - __url__ = 'http://msdn.microsoft.com/en-us/library/office/ff837902.aspx' - - __members__ = ( - XmlMappedEnumMember( - 'PORTRAIT', 0, 'portrait', 'Portrait orientation.' - ), - XmlMappedEnumMember( - 'LANDSCAPE', 1, 'landscape', 'Landscape orientation.' - ), - ) - - -@alias('WD_SECTION') -class WD_SECTION_START(XmlEnumeration): - """ - alias: **WD_SECTION** - - Specifies the start type of a section break. - - Example:: - - from docx.enum.section import WD_SECTION - - section = document.sections[0] - section.start_type = WD_SECTION.NEW_PAGE - """ - - __ms_name__ = 'WdSectionStart' - - __url__ = 'http://msdn.microsoft.com/en-us/library/office/ff840975.aspx' - - __members__ = ( - XmlMappedEnumMember( - 'CONTINUOUS', 0, 'continuous', 'Continuous section break.' - ), - XmlMappedEnumMember( - 'NEW_COLUMN', 1, 'nextColumn', 'New column section break.' - ), - XmlMappedEnumMember( - 'NEW_PAGE', 2, 'nextPage', 'New page section break.' - ), - XmlMappedEnumMember( - 'EVEN_PAGE', 3, 'evenPage', 'Even pages section break.' - ), - XmlMappedEnumMember( - 'ODD_PAGE', 4, 'oddPage', 'Section begins on next odd page.' - ), - ) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_a_v_a_r.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_a_v_a_r.py deleted file mode 100644 index 39039cf73a5346db144f39bd8c046a76bd52af31..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_a_v_a_r.py +++ /dev/null @@ -1,138 +0,0 @@ -from fontTools.misc import sstruct -from fontTools.misc.fixedTools import ( - fixedToFloat as fi2fl, - floatToFixed as fl2fi, - floatToFixedToStr as fl2str, - strToFixedToFloat as str2fl, -) -from fontTools.misc.textTools import bytesjoin, safeEval -from fontTools.ttLib import TTLibError -from . import DefaultTable -from . import otTables -import struct -import logging - - -log = logging.getLogger(__name__) - -from .otBase import BaseTTXConverter - - -class table__a_v_a_r(BaseTTXConverter): - """Axis Variations Table - - This class represents the ``avar`` table of a variable font. The object has one - substantive attribute, ``segments``, which maps axis tags to a segments dictionary:: - - >>> font["avar"].segments # doctest: +SKIP - {'wght': {-1.0: -1.0, - 0.0: 0.0, - 0.125: 0.11444091796875, - 0.25: 0.23492431640625, - 0.5: 0.35540771484375, - 0.625: 0.5, - 0.75: 0.6566162109375, - 0.875: 0.81927490234375, - 1.0: 1.0}, - 'ital': {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}} - - Notice that the segments dictionary is made up of normalized values. A valid - ``avar`` segment mapping must contain the entries ``-1.0: -1.0, 0.0: 0.0, 1.0: 1.0``. - fontTools does not enforce this, so it is your responsibility to ensure that - mappings are valid. - """ - - dependencies = ["fvar"] - - def __init__(self, tag=None): - super().__init__(tag) - self.segments = {} - - def compile(self, ttFont): - axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] - if not hasattr(self, "table"): - self.table = otTables.avar() - if not hasattr(self.table, "Reserved"): - self.table.Reserved = 0 - self.table.Version = (getattr(self, "majorVersion", 1) << 16) | getattr( - self, "minorVersion", 0 - ) - self.table.AxisCount = len(axisTags) - self.table.AxisSegmentMap = [] - for axis in axisTags: - mappings = self.segments[axis] - segmentMap = otTables.AxisSegmentMap() - segmentMap.PositionMapCount = len(mappings) - segmentMap.AxisValueMap = [] - for key, value in sorted(mappings.items()): - valueMap = otTables.AxisValueMap() - valueMap.FromCoordinate = key - valueMap.ToCoordinate = value - segmentMap.AxisValueMap.append(valueMap) - self.table.AxisSegmentMap.append(segmentMap) - return super().compile(ttFont) - - def decompile(self, data, ttFont): - super().decompile(data, ttFont) - assert self.table.Version >= 0x00010000 - self.majorVersion = self.table.Version >> 16 - self.minorVersion = self.table.Version & 0xFFFF - axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] - for axis in axisTags: - self.segments[axis] = {} - for axis, segmentMap in zip(axisTags, self.table.AxisSegmentMap): - segments = self.segments[axis] = {} - for segment in segmentMap.AxisValueMap: - segments[segment.FromCoordinate] = segment.ToCoordinate - - def toXML(self, writer, ttFont): - writer.simpletag( - "version", - major=getattr(self, "majorVersion", 1), - minor=getattr(self, "minorVersion", 0), - ) - writer.newline() - axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] - for axis in axisTags: - writer.begintag("segment", axis=axis) - writer.newline() - for key, value in sorted(self.segments[axis].items()): - key = fl2str(key, 14) - value = fl2str(value, 14) - writer.simpletag("mapping", **{"from": key, "to": value}) - writer.newline() - writer.endtag("segment") - writer.newline() - if getattr(self, "majorVersion", 1) >= 2: - if self.table.VarIdxMap: - self.table.VarIdxMap.toXML(writer, ttFont, name="VarIdxMap") - if self.table.VarStore: - self.table.VarStore.toXML(writer, ttFont) - - def fromXML(self, name, attrs, content, ttFont): - if not hasattr(self, "table"): - self.table = otTables.avar() - if not hasattr(self.table, "Reserved"): - self.table.Reserved = 0 - if name == "version": - self.majorVersion = safeEval(attrs["major"]) - self.minorVersion = safeEval(attrs["minor"]) - self.table.Version = (getattr(self, "majorVersion", 1) << 16) | getattr( - self, "minorVersion", 0 - ) - elif name == "segment": - axis = attrs["axis"] - segment = self.segments[axis] = {} - for element in content: - if isinstance(element, tuple): - elementName, elementAttrs, _ = element - if elementName == "mapping": - fromValue = str2fl(elementAttrs["from"], 14) - toValue = str2fl(elementAttrs["to"], 14) - if fromValue in segment: - log.warning( - "duplicate entry for %s in axis '%s'", fromValue, axis - ) - segment[fromValue] = toValue - else: - super().fromXML(name, attrs, content, ttFont) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fsspec/compression.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fsspec/compression.py deleted file mode 100644 index afa0f41156e16f35f0062e78973d9ddd2de8bc01..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fsspec/compression.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Helper functions for a standard streaming compression API""" -from bz2 import BZ2File -from zipfile import ZipFile - -import fsspec.utils -from fsspec.spec import AbstractBufferedFile - - -def noop_file(file, mode, **kwargs): - return file - - -# TODO: files should also be available as contexts -# should be functions of the form func(infile, mode=, **kwargs) -> file-like -compr = {None: noop_file} - - -def register_compression(name, callback, extensions, force=False): - """Register an "inferable" file compression type. - - Registers transparent file compression type for use with fsspec.open. - Compression can be specified by name in open, or "infer"-ed for any files - ending with the given extensions. - - Args: - name: (str) The compression type name. Eg. "gzip". - callback: A callable of form (infile, mode, **kwargs) -> file-like. - Accepts an input file-like object, the target mode and kwargs. - Returns a wrapped file-like object. - extensions: (str, Iterable[str]) A file extension, or list of file - extensions for which to infer this compression scheme. Eg. "gz". - force: (bool) Force re-registration of compression type or extensions. - - Raises: - ValueError: If name or extensions already registered, and not force. - - """ - if isinstance(extensions, str): - extensions = [extensions] - - # Validate registration - if name in compr and not force: - raise ValueError("Duplicate compression registration: %s" % name) - - for ext in extensions: - if ext in fsspec.utils.compressions and not force: - raise ValueError( - "Duplicate compression file extension: %s (%s)" % (ext, name) - ) - - compr[name] = callback - - for ext in extensions: - fsspec.utils.compressions[ext] = name - - -def unzip(infile, mode="rb", filename=None, **kwargs): - if "r" not in mode: - filename = filename or "file" - z = ZipFile(infile, mode="w", **kwargs) - fo = z.open(filename, mode="w") - fo.close = lambda closer=fo.close: closer() or z.close() - return fo - z = ZipFile(infile) - if filename is None: - filename = z.namelist()[0] - return z.open(filename, mode="r", **kwargs) - - -register_compression("zip", unzip, "zip") -register_compression("bz2", BZ2File, "bz2") - -try: # pragma: no cover - from isal import igzip - - def isal(infile, mode="rb", **kwargs): - return igzip.IGzipFile(fileobj=infile, mode=mode, **kwargs) - - register_compression("gzip", isal, "gz") -except ImportError: - from gzip import GzipFile - - register_compression( - "gzip", lambda f, **kwargs: GzipFile(fileobj=f, **kwargs), "gz" - ) - -try: - from lzma import LZMAFile - - register_compression("lzma", LZMAFile, "xz") - register_compression("xz", LZMAFile, "xz", force=True) -except ImportError: - pass - -try: - import lzmaffi - - register_compression("lzma", lzmaffi.LZMAFile, "xz", force=True) - register_compression("xz", lzmaffi.LZMAFile, "xz", force=True) -except ImportError: - pass - - -class SnappyFile(AbstractBufferedFile): - def __init__(self, infile, mode, **kwargs): - import snappy - - super().__init__( - fs=None, path="snappy", mode=mode.strip("b") + "b", size=999999999, **kwargs - ) - self.infile = infile - if "r" in mode: - self.codec = snappy.StreamDecompressor() - else: - self.codec = snappy.StreamCompressor() - - def _upload_chunk(self, final=False): - self.buffer.seek(0) - out = self.codec.add_chunk(self.buffer.read()) - self.infile.write(out) - return True - - def seek(self, loc, whence=0): - raise NotImplementedError("SnappyFile is not seekable") - - def seekable(self): - return False - - def _fetch_range(self, start, end): - """Get the specified set of bytes from remote""" - data = self.infile.read(end - start) - return self.codec.decompress(data) - - -try: - import snappy - - snappy.compress - # Snappy may use the .sz file extension, but this is not part of the - # standard implementation. - register_compression("snappy", SnappyFile, []) - -except (ImportError, NameError, AttributeError): - pass - -try: - import lz4.frame - - register_compression("lz4", lz4.frame.open, "lz4") -except ImportError: - pass - -try: - import zstandard as zstd - - def zstandard_file(infile, mode="rb"): - if "r" in mode: - cctx = zstd.ZstdDecompressor() - return cctx.stream_reader(infile) - else: - cctx = zstd.ZstdCompressor(level=10) - return cctx.stream_writer(infile) - - register_compression("zstd", zstandard_file, "zst") -except ImportError: - pass - - -def available_compressions(): - """Return a list of the implemented compressions.""" - return list(compr) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/Download-a587c81f.js b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/Download-a587c81f.js deleted file mode 100644 index 14c7032e2e362dfbc0c1d4590e6a18c19c1d8e4e..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/Download-a587c81f.js +++ /dev/null @@ -1,2 +0,0 @@ -import{S as i,e as p,s as v,J as o,K as e,p as h,M as c,n,A as m}from"./index-f877dfd5.js";function d(l){let t,s;return{c(){t=o("svg"),s=o("path"),e(s,"fill","currentColor"),e(s,"d","M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4zm0-10l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10l10-10z"),e(t,"xmlns","http://www.w3.org/2000/svg"),e(t,"width","100%"),e(t,"height","100%"),e(t,"viewBox","0 0 32 32")},m(a,r){h(a,t,r),c(t,s)},p:n,i:n,o:n,d(a){a&&m(t)}}}class u extends i{constructor(t){super(),p(this,t,null,d,v,{})}}export{u as D}; -//# sourceMappingURL=Download-a587c81f.js.map diff --git a/spaces/cihyFjudo/fairness-paper-search/Download nghe thuat ban hang bac cao pdf les secrets du succs de Zig Ziglar.md b/spaces/cihyFjudo/fairness-paper-search/Download nghe thuat ban hang bac cao pdf les secrets du succs de Zig Ziglar.md deleted file mode 100644 index c33d25eb827d799febd805eacbaa0ba7e1080001..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Download nghe thuat ban hang bac cao pdf les secrets du succs de Zig Ziglar.md +++ /dev/null @@ -1,6 +0,0 @@ -

download nghe thuat ban hang bac cao pdf


DOWNLOADhttps://tinurli.com/2uwjD0



- - aaccfb2cb3
-
-
-

diff --git a/spaces/cihyFjudo/fairness-paper-search/Moi3d-V2-License-Key-Added.md b/spaces/cihyFjudo/fairness-paper-search/Moi3d-V2-License-Key-Added.md deleted file mode 100644 index 55d1b9a997c21a4b527aa6086b03c7b21c33be19..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Moi3d-V2-License-Key-Added.md +++ /dev/null @@ -1,70 +0,0 @@ -## Moi3d V2 License Key Added - - - - - - - - - -**Download » [https://smitodoutcu.blogspot.com/?c=2txleg](https://smitodoutcu.blogspot.com/?c=2txleg)** - - - - - - - - - - - - - -# Moi3d V2 License Key Added: What You Need to Know - - - -Moi3d is a 3D modeling software that is designed to be easy to use and intuitive. It is especially suitable for creating smooth and organic shapes. Moi3d V2 is the latest version of the software, which has many new features and improvements. - - - -One of the most important things you need to know about Moi3d V2 is that it requires a license key to activate. A license key is a unique code that you enter when you install or run the software for the first time. It verifies that you have purchased a valid copy of the software and allows you to use it without any limitations. - - - -If you have already purchased Moi3d V1, you can upgrade to Moi3d V2 for a discounted price. You will need to provide your V1 license key when you order the upgrade. You will then receive a new V2 license key by email. You can use this key to activate Moi3d V2 on your computer. - - - -If you want to use Moi3d V2 on more than one computer, you will need to purchase a second or any additional commercial license for a 25% discount. You will receive a separate license key for each computer. You can also transfer your license key from one computer to another by deleting the previous license information from both the application data folder and the registry. You can find detailed instructions on how to do this on the Moi3d discussion forum[^1^]. - - - -Moi3d V2 license key is a valuable asset that allows you to enjoy the full potential of the software. It is also a way of supporting the development of Moi3d and ensuring its future updates and enhancements. Therefore, you should keep your license key safe and secure, and avoid sharing it with anyone else. - - - -Some of the features that make Moi3d V2 stand out from other 3D modeling software are: - - - -- Streamlined UI: Moi3d has a simple and intuitive user interface that allows you to access all the tools and options with minimal clicks and mouse movements. You can also customize the UI to suit your preferences and workflow. The UI is designed to be fast and fluid, without any lag or slowdowns. - -- Powerful yet easy to use: Moi3d is based on NURBS (Non-Uniform Rational B-Splines) technology, which is a mathematical method of creating smooth and precise curves and surfaces. NURBS modeling is ideal for creating organic and mechanical shapes that are hard to achieve with polygon modeling. Moi3d makes NURBS modeling easy and accessible, with a set of tools that are simple to use but powerful enough to create complex models. - -- Unique polygon mesh export: Moi3d has a built-in polygon mesh exporter that can convert your NURBS models into clean and optimized polygon meshes. The exporter can generate N-Gon (polygon with more than four sides) meshes that preserve the sharpness and smoothness of your models. You can also adjust the level of detail and control the mesh topology. The exported meshes can be used in other 3D software for animation, rendering, or game development. - -- Cross-platform compatibility: Moi3d V2 is available for both Windows and Mac OS X platforms. It also supports different graphics APIs, such as Direct3D9 and Metal, which can improve the performance and stability of the software depending on your system. You can also copy and paste SVG (Scalable Vector Graphics) format between Moi3d and other applications. - - - -Moi3d V2 is a versatile and affordable 3D modeling software that can cater to different needs and preferences of designers and artists. It is a great complement to polygon-based software, as it can create models that are hard or impossible to make with polygons. It is also a great standalone software, as it can export high-quality polygon meshes that can be used in other 3D applications. - - 1b8d091108 - - - - - diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/PIL/ImageTransform.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/PIL/ImageTransform.py deleted file mode 100644 index 7881f0d262b0db7ecaed224ee2268f3b69b836c9..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/PIL/ImageTransform.py +++ /dev/null @@ -1,102 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# transform wrappers -# -# History: -# 2002-04-08 fl Created -# -# Copyright (c) 2002 by Secret Labs AB -# Copyright (c) 2002 by Fredrik Lundh -# -# See the README file for information on usage and redistribution. -# - -from . import Image - - -class Transform(Image.ImageTransformHandler): - def __init__(self, data): - self.data = data - - def getdata(self): - return self.method, self.data - - def transform(self, size, image, **options): - # can be overridden - method, data = self.getdata() - return image.transform(size, method, data, **options) - - -class AffineTransform(Transform): - """ - Define an affine image transform. - - This function takes a 6-tuple (a, b, c, d, e, f) which contain the first - two rows from an affine transform matrix. For each pixel (x, y) in the - output image, the new value is taken from a position (a x + b y + c, - d x + e y + f) in the input image, rounded to nearest pixel. - - This function can be used to scale, translate, rotate, and shear the - original image. - - See :py:meth:`~PIL.Image.Image.transform` - - :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows - from an affine transform matrix. - """ - - method = Image.Transform.AFFINE - - -class ExtentTransform(Transform): - """ - Define a transform to extract a subregion from an image. - - Maps a rectangle (defined by two corners) from the image to a rectangle of - the given size. The resulting image will contain data sampled from between - the corners, such that (x0, y0) in the input image will end up at (0,0) in - the output image, and (x1, y1) at size. - - This method can be used to crop, stretch, shrink, or mirror an arbitrary - rectangle in the current image. It is slightly slower than crop, but about - as fast as a corresponding resize operation. - - See :py:meth:`~PIL.Image.Image.transform` - - :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the - input image's coordinate system. See :ref:`coordinate-system`. - """ - - method = Image.Transform.EXTENT - - -class QuadTransform(Transform): - """ - Define a quad image transform. - - Maps a quadrilateral (a region defined by four corners) from the image to a - rectangle of the given size. - - See :py:meth:`~PIL.Image.Image.transform` - - :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the - upper left, lower left, lower right, and upper right corner of the - source quadrilateral. - """ - - method = Image.Transform.QUAD - - -class MeshTransform(Transform): - """ - Define a mesh image transform. A mesh transform consists of one or more - individual quad transforms. - - See :py:meth:`~PIL.Image.Image.transform` - - :param data: A list of (bbox, quad) tuples. - """ - - method = Image.Transform.MESH diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/_n_a_m_e.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/_n_a_m_e.py deleted file mode 100644 index 0846659a53a372059a001dfb774041f90c361aaa..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/tables/_n_a_m_e.py +++ /dev/null @@ -1,1226 +0,0 @@ -# -*- coding: utf-8 -*- -from fontTools.misc import sstruct -from fontTools.misc.textTools import ( - bytechr, - byteord, - bytesjoin, - strjoin, - tobytes, - tostr, - safeEval, -) -from fontTools.misc.encodingTools import getEncoding -from fontTools.ttLib import newTable -from fontTools.ttLib.ttVisitor import TTVisitor -from fontTools import ttLib -import fontTools.ttLib.tables.otTables as otTables -from fontTools.ttLib.tables import C_P_A_L_ -from . import DefaultTable -import struct -import logging - - -log = logging.getLogger(__name__) - -nameRecordFormat = """ - > # big endian - platformID: H - platEncID: H - langID: H - nameID: H - length: H - offset: H -""" - -nameRecordSize = sstruct.calcsize(nameRecordFormat) - - -class table__n_a_m_e(DefaultTable.DefaultTable): - dependencies = ["ltag"] - - def decompile(self, data, ttFont): - format, n, stringOffset = struct.unpack(b">HHH", data[:6]) - expectedStringOffset = 6 + n * nameRecordSize - if stringOffset != expectedStringOffset: - log.error( - "'name' table stringOffset incorrect. Expected: %s; Actual: %s", - expectedStringOffset, - stringOffset, - ) - stringData = data[stringOffset:] - data = data[6:] - self.names = [] - for i in range(n): - if len(data) < 12: - log.error("skipping malformed name record #%d", i) - continue - name, data = sstruct.unpack2(nameRecordFormat, data, NameRecord()) - name.string = stringData[name.offset : name.offset + name.length] - if name.offset + name.length > len(stringData): - log.error("skipping malformed name record #%d", i) - continue - assert len(name.string) == name.length - # if (name.platEncID, name.platformID) in ((0, 0), (1, 3)): - # if len(name.string) % 2: - # print "2-byte string doesn't have even length!" - # print name.__dict__ - del name.offset, name.length - self.names.append(name) - - def compile(self, ttFont): - if not hasattr(self, "names"): - # only happens when there are NO name table entries read - # from the TTX file - self.names = [] - names = self.names - names.sort() # sort according to the spec; see NameRecord.__lt__() - stringData = b"" - format = 0 - n = len(names) - stringOffset = 6 + n * sstruct.calcsize(nameRecordFormat) - data = struct.pack(b">HHH", format, n, stringOffset) - lastoffset = 0 - done = {} # remember the data so we can reuse the "pointers" - for name in names: - string = name.toBytes() - if string in done: - name.offset, name.length = done[string] - else: - name.offset, name.length = done[string] = len(stringData), len(string) - stringData = bytesjoin([stringData, string]) - data = data + sstruct.pack(nameRecordFormat, name) - return data + stringData - - def toXML(self, writer, ttFont): - for name in self.names: - name.toXML(writer, ttFont) - - def fromXML(self, name, attrs, content, ttFont): - if name != "namerecord": - return # ignore unknown tags - if not hasattr(self, "names"): - self.names = [] - name = NameRecord() - self.names.append(name) - name.fromXML(name, attrs, content, ttFont) - - def getName(self, nameID, platformID, platEncID, langID=None): - for namerecord in self.names: - if ( - namerecord.nameID == nameID - and namerecord.platformID == platformID - and namerecord.platEncID == platEncID - ): - if langID is None or namerecord.langID == langID: - return namerecord - return None # not found - - def getDebugName(self, nameID): - englishName = someName = None - for name in self.names: - if name.nameID != nameID: - continue - try: - unistr = name.toUnicode() - except UnicodeDecodeError: - continue - - someName = unistr - if (name.platformID, name.langID) in ((1, 0), (3, 0x409)): - englishName = unistr - break - if englishName: - return englishName - elif someName: - return someName - else: - return None - - def getFirstDebugName(self, nameIDs): - for nameID in nameIDs: - name = self.getDebugName(nameID) - if name is not None: - return name - return None - - def getBestFamilyName(self): - # 21 = WWS Family Name - # 16 = Typographic Family Name - # 1 = Family Name - return self.getFirstDebugName((21, 16, 1)) - - def getBestSubFamilyName(self): - # 22 = WWS SubFamily Name - # 17 = Typographic SubFamily Name - # 2 = SubFamily Name - return self.getFirstDebugName((22, 17, 2)) - - def getBestFullName(self): - # 4 = Full Name - # 6 = PostScript Name - for nameIDs in ((21, 22), (16, 17), (1, 2), (4,), (6,)): - if len(nameIDs) == 2: - name_fam = self.getDebugName(nameIDs[0]) - name_subfam = self.getDebugName(nameIDs[1]) - if None in [name_fam, name_subfam]: - continue # if any is None, skip - name = f"{name_fam} {name_subfam}" - if name_subfam.lower() == "regular": - name = f"{name_fam}" - return name - else: - name = self.getDebugName(nameIDs[0]) - if name is not None: - return name - return None - - def setName(self, string, nameID, platformID, platEncID, langID): - """Set the 'string' for the name record identified by 'nameID', 'platformID', - 'platEncID' and 'langID'. If a record with that nameID doesn't exist, create it - and append to the name table. - - 'string' can be of type `str` (`unicode` in PY2) or `bytes`. In the latter case, - it is assumed to be already encoded with the correct plaform-specific encoding - identified by the (platformID, platEncID, langID) triplet. A warning is issued - to prevent unexpected results. - """ - if not hasattr(self, "names"): - self.names = [] - if not isinstance(string, str): - if isinstance(string, bytes): - log.warning( - "name string is bytes, ensure it's correctly encoded: %r", string - ) - else: - raise TypeError( - "expected unicode or bytes, found %s: %r" - % (type(string).__name__, string) - ) - namerecord = self.getName(nameID, platformID, platEncID, langID) - if namerecord: - namerecord.string = string - else: - self.names.append(makeName(string, nameID, platformID, platEncID, langID)) - - def removeNames(self, nameID=None, platformID=None, platEncID=None, langID=None): - """Remove any name records identified by the given combination of 'nameID', - 'platformID', 'platEncID' and 'langID'. - """ - args = { - argName: argValue - for argName, argValue in ( - ("nameID", nameID), - ("platformID", platformID), - ("platEncID", platEncID), - ("langID", langID), - ) - if argValue is not None - } - if not args: - # no arguments, nothing to do - return - self.names = [ - rec - for rec in self.names - if any( - argValue != getattr(rec, argName) for argName, argValue in args.items() - ) - ] - - @staticmethod - def removeUnusedNames(ttFont): - """Remove any name records which are not in NameID range 0-255 and not utilized - within the font itself.""" - visitor = NameRecordVisitor() - visitor.visit(ttFont) - toDelete = set() - for record in ttFont["name"].names: - # Name IDs 26 to 255, inclusive, are reserved for future standard names. - # https://learn.microsoft.com/en-us/typography/opentype/spec/name#name-ids - if record.nameID < 256: - continue - if record.nameID not in visitor.seen: - toDelete.add(record.nameID) - - for nameID in toDelete: - ttFont["name"].removeNames(nameID) - return toDelete - - def _findUnusedNameID(self, minNameID=256): - """Finds an unused name id. - - The nameID is assigned in the range between 'minNameID' and 32767 (inclusive), - following the last nameID in the name table. - """ - names = getattr(self, "names", []) - nameID = 1 + max([n.nameID for n in names] + [minNameID - 1]) - if nameID > 32767: - raise ValueError("nameID must be less than 32768") - return nameID - - def findMultilingualName(self, names, windows=True, mac=True, minNameID=0): - """Return the name ID of an existing multilingual name that - matches the 'names' dictionary, or None if not found. - - 'names' is a dictionary with the name in multiple languages, - such as {'en': 'Pale', 'de': 'Blaß', 'de-CH': 'Blass'}. - The keys can be arbitrary IETF BCP 47 language codes; - the values are Unicode strings. - - If 'windows' is True, the returned name ID is guaranteed - exist for all requested languages for platformID=3 and - platEncID=1. - If 'mac' is True, the returned name ID is guaranteed to exist - for all requested languages for platformID=1 and platEncID=0. - - The returned name ID will not be less than the 'minNameID' - argument. - """ - # Gather the set of requested - # (string, platformID, platEncID, langID) - # tuples - reqNameSet = set() - for lang, name in sorted(names.items()): - if windows: - windowsName = _makeWindowsName(name, None, lang) - if windowsName is not None: - reqNameSet.add( - ( - windowsName.string, - windowsName.platformID, - windowsName.platEncID, - windowsName.langID, - ) - ) - if mac: - macName = _makeMacName(name, None, lang) - if macName is not None: - reqNameSet.add( - ( - macName.string, - macName.platformID, - macName.platEncID, - macName.langID, - ) - ) - - # Collect matching name IDs - matchingNames = dict() - for name in self.names: - try: - key = (name.toUnicode(), name.platformID, name.platEncID, name.langID) - except UnicodeDecodeError: - continue - if key in reqNameSet and name.nameID >= minNameID: - nameSet = matchingNames.setdefault(name.nameID, set()) - nameSet.add(key) - - # Return the first name ID that defines all requested strings - for nameID, nameSet in sorted(matchingNames.items()): - if nameSet == reqNameSet: - return nameID - - return None # not found - - def addMultilingualName( - self, names, ttFont=None, nameID=None, windows=True, mac=True, minNameID=0 - ): - """Add a multilingual name, returning its name ID - - 'names' is a dictionary with the name in multiple languages, - such as {'en': 'Pale', 'de': 'Blaß', 'de-CH': 'Blass'}. - The keys can be arbitrary IETF BCP 47 language codes; - the values are Unicode strings. - - 'ttFont' is the TTFont to which the names are added, or None. - If present, the font's 'ltag' table can get populated - to store exotic language codes, which allows encoding - names that otherwise cannot get encoded at all. - - 'nameID' is the name ID to be used, or None to let the library - find an existing set of name records that match, or pick an - unused name ID. - - If 'windows' is True, a platformID=3 name record will be added. - If 'mac' is True, a platformID=1 name record will be added. - - If the 'nameID' argument is None, the created nameID will not - be less than the 'minNameID' argument. - """ - if not hasattr(self, "names"): - self.names = [] - if nameID is None: - # Reuse nameID if possible - nameID = self.findMultilingualName( - names, windows=windows, mac=mac, minNameID=minNameID - ) - if nameID is not None: - return nameID - nameID = self._findUnusedNameID() - # TODO: Should minimize BCP 47 language codes. - # https://github.com/fonttools/fonttools/issues/930 - for lang, name in sorted(names.items()): - if windows: - windowsName = _makeWindowsName(name, nameID, lang) - if windowsName is not None: - self.names.append(windowsName) - else: - # We cannot not make a Windows name: make sure we add a - # Mac name as a fallback. This can happen for exotic - # BCP47 language tags that have no Windows language code. - mac = True - if mac: - macName = _makeMacName(name, nameID, lang, ttFont) - if macName is not None: - self.names.append(macName) - return nameID - - def addName(self, string, platforms=((1, 0, 0), (3, 1, 0x409)), minNameID=255): - """Add a new name record containing 'string' for each (platformID, platEncID, - langID) tuple specified in the 'platforms' list. - - The nameID is assigned in the range between 'minNameID'+1 and 32767 (inclusive), - following the last nameID in the name table. - If no 'platforms' are specified, two English name records are added, one for the - Macintosh (platformID=0), and one for the Windows platform (3). - - The 'string' must be a Unicode string, so it can be encoded with different, - platform-specific encodings. - - Return the new nameID. - """ - assert ( - len(platforms) > 0 - ), "'platforms' must contain at least one (platformID, platEncID, langID) tuple" - if not hasattr(self, "names"): - self.names = [] - if not isinstance(string, str): - raise TypeError( - "expected str, found %s: %r" % (type(string).__name__, string) - ) - nameID = self._findUnusedNameID(minNameID + 1) - for platformID, platEncID, langID in platforms: - self.names.append(makeName(string, nameID, platformID, platEncID, langID)) - return nameID - - -def makeName(string, nameID, platformID, platEncID, langID): - name = NameRecord() - name.string, name.nameID, name.platformID, name.platEncID, name.langID = ( - string, - nameID, - platformID, - platEncID, - langID, - ) - return name - - -def _makeWindowsName(name, nameID, language): - """Create a NameRecord for the Microsoft Windows platform - - 'language' is an arbitrary IETF BCP 47 language identifier such - as 'en', 'de-CH', 'de-AT-1901', or 'fa-Latn'. If Microsoft Windows - does not support the desired language, the result will be None. - Future versions of fonttools might return a NameRecord for the - OpenType 'name' table format 1, but this is not implemented yet. - """ - langID = _WINDOWS_LANGUAGE_CODES.get(language.lower()) - if langID is not None: - return makeName(name, nameID, 3, 1, langID) - else: - log.warning( - "cannot add Windows name in language %s " - "because fonttools does not yet support " - "name table format 1" % language - ) - return None - - -def _makeMacName(name, nameID, language, font=None): - """Create a NameRecord for Apple platforms - - 'language' is an arbitrary IETF BCP 47 language identifier such - as 'en', 'de-CH', 'de-AT-1901', or 'fa-Latn'. When possible, we - create a Macintosh NameRecord that is understood by old applications - (platform ID 1 and an old-style Macintosh language enum). If this - is not possible, we create a Unicode NameRecord (platform ID 0) - whose language points to the font’s 'ltag' table. The latter - can encode any string in any language, but legacy applications - might not recognize the format (in which case they will ignore - those names). - - 'font' should be the TTFont for which you want to create a name. - If 'font' is None, we only return NameRecords for legacy Macintosh; - in that case, the result will be None for names that need to - be encoded with an 'ltag' table. - - See the section “The language identifier” in Apple’s specification: - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html - """ - macLang = _MAC_LANGUAGE_CODES.get(language.lower()) - macScript = _MAC_LANGUAGE_TO_SCRIPT.get(macLang) - if macLang is not None and macScript is not None: - encoding = getEncoding(1, macScript, macLang, default="ascii") - # Check if we can actually encode this name. If we can't, - # for example because we have no support for the legacy - # encoding, or because the name string contains Unicode - # characters that the legacy encoding cannot represent, - # we fall back to encoding the name in Unicode and put - # the language tag into the ltag table. - try: - _ = tobytes(name, encoding, errors="strict") - return makeName(name, nameID, 1, macScript, macLang) - except UnicodeEncodeError: - pass - if font is not None: - ltag = font.tables.get("ltag") - if ltag is None: - ltag = font["ltag"] = newTable("ltag") - # 0 = Unicode; 4 = “Unicode 2.0 or later semantics (non-BMP characters allowed)” - # “The preferred platform-specific code for Unicode would be 3 or 4.” - # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html - return makeName(name, nameID, 0, 4, ltag.addTag(language)) - else: - log.warning( - "cannot store language %s into 'ltag' table " - "without having access to the TTFont object" % language - ) - return None - - -class NameRecord(object): - def getEncoding(self, default="ascii"): - """Returns the Python encoding name for this name entry based on its platformID, - platEncID, and langID. If encoding for these values is not known, by default - 'ascii' is returned. That can be overriden by passing a value to the default - argument. - """ - return getEncoding(self.platformID, self.platEncID, self.langID, default) - - def encodingIsUnicodeCompatible(self): - return self.getEncoding(None) in ["utf_16_be", "ucs2be", "ascii", "latin1"] - - def __str__(self): - return self.toStr(errors="backslashreplace") - - def isUnicode(self): - return self.platformID == 0 or ( - self.platformID == 3 and self.platEncID in [0, 1, 10] - ) - - def toUnicode(self, errors="strict"): - """ - If self.string is a Unicode string, return it; otherwise try decoding the - bytes in self.string to a Unicode string using the encoding of this - entry as returned by self.getEncoding(); Note that self.getEncoding() - returns 'ascii' if the encoding is unknown to the library. - - Certain heuristics are performed to recover data from bytes that are - ill-formed in the chosen encoding, or that otherwise look misencoded - (mostly around bad UTF-16BE encoded bytes, or bytes that look like UTF-16BE - but marked otherwise). If the bytes are ill-formed and the heuristics fail, - the error is handled according to the errors parameter to this function, which is - passed to the underlying decode() function; by default it throws a - UnicodeDecodeError exception. - - Note: The mentioned heuristics mean that roundtripping a font to XML and back - to binary might recover some misencoded data whereas just loading the font - and saving it back will not change them. - """ - - def isascii(b): - return (b >= 0x20 and b <= 0x7E) or b in [0x09, 0x0A, 0x0D] - - encoding = self.getEncoding() - string = self.string - - if ( - isinstance(string, bytes) - and encoding == "utf_16_be" - and len(string) % 2 == 1 - ): - # Recover badly encoded UTF-16 strings that have an odd number of bytes: - # - If the last byte is zero, drop it. Otherwise, - # - If all the odd bytes are zero and all the even bytes are ASCII, - # prepend one zero byte. Otherwise, - # - If first byte is zero and all other bytes are ASCII, insert zero - # bytes between consecutive ASCII bytes. - # - # (Yes, I've seen all of these in the wild... sigh) - if byteord(string[-1]) == 0: - string = string[:-1] - elif all( - byteord(b) == 0 if i % 2 else isascii(byteord(b)) - for i, b in enumerate(string) - ): - string = b"\0" + string - elif byteord(string[0]) == 0 and all( - isascii(byteord(b)) for b in string[1:] - ): - string = bytesjoin(b"\0" + bytechr(byteord(b)) for b in string[1:]) - - string = tostr(string, encoding=encoding, errors=errors) - - # If decoded strings still looks like UTF-16BE, it suggests a double-encoding. - # Fix it up. - if all( - ord(c) == 0 if i % 2 == 0 else isascii(ord(c)) for i, c in enumerate(string) - ): - # If string claims to be Mac encoding, but looks like UTF-16BE with ASCII text, - # narrow it down. - string = "".join(c for c in string[1::2]) - - return string - - def toBytes(self, errors="strict"): - """If self.string is a bytes object, return it; otherwise try encoding - the Unicode string in self.string to bytes using the encoding of this - entry as returned by self.getEncoding(); Note that self.getEncoding() - returns 'ascii' if the encoding is unknown to the library. - - If the Unicode string cannot be encoded to bytes in the chosen encoding, - the error is handled according to the errors parameter to this function, - which is passed to the underlying encode() function; by default it throws a - UnicodeEncodeError exception. - """ - return tobytes(self.string, encoding=self.getEncoding(), errors=errors) - - toStr = toUnicode - - def toXML(self, writer, ttFont): - try: - unistr = self.toUnicode() - except UnicodeDecodeError: - unistr = None - attrs = [ - ("nameID", self.nameID), - ("platformID", self.platformID), - ("platEncID", self.platEncID), - ("langID", hex(self.langID)), - ] - - if unistr is None or not self.encodingIsUnicodeCompatible(): - attrs.append(("unicode", unistr is not None)) - - writer.begintag("namerecord", attrs) - writer.newline() - if unistr is not None: - writer.write(unistr) - else: - writer.write8bit(self.string) - writer.newline() - writer.endtag("namerecord") - writer.newline() - - def fromXML(self, name, attrs, content, ttFont): - self.nameID = safeEval(attrs["nameID"]) - self.platformID = safeEval(attrs["platformID"]) - self.platEncID = safeEval(attrs["platEncID"]) - self.langID = safeEval(attrs["langID"]) - s = strjoin(content).strip() - encoding = self.getEncoding() - if self.encodingIsUnicodeCompatible() or safeEval( - attrs.get("unicode", "False") - ): - self.string = s.encode(encoding) - else: - # This is the inverse of write8bit... - self.string = s.encode("latin1") - - def __lt__(self, other): - if type(self) != type(other): - return NotImplemented - - try: - selfTuple = ( - self.platformID, - self.platEncID, - self.langID, - self.nameID, - ) - otherTuple = ( - other.platformID, - other.platEncID, - other.langID, - other.nameID, - ) - except AttributeError: - # This can only happen for - # 1) an object that is not a NameRecord, or - # 2) an unlikely incomplete NameRecord object which has not been - # fully populated - return NotImplemented - - try: - # Include the actual NameRecord string in the comparison tuples - selfTuple = selfTuple + (self.toBytes(),) - otherTuple = otherTuple + (other.toBytes(),) - except UnicodeEncodeError as e: - # toBytes caused an encoding error in either of the two, so content - # to sorting based on IDs only - log.error("NameRecord sorting failed to encode: %s" % e) - - # Implemented so that list.sort() sorts according to the spec by using - # the order of the tuple items and their comparison - return selfTuple < otherTuple - - def __repr__(self): - return "" % ( - self.nameID, - self.platformID, - self.langID, - ) - - -# Windows language ID → IETF BCP-47 language tag -# -# While Microsoft indicates a region/country for all its language -# IDs, we follow Unicode practice by omitting “most likely subtags” -# as per Unicode CLDR. For example, English is simply “en” and not -# “en-Latn” because according to Unicode, the default script -# for English is Latin. -# -# http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html -# http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry -_WINDOWS_LANGUAGES = { - 0x0436: "af", - 0x041C: "sq", - 0x0484: "gsw", - 0x045E: "am", - 0x1401: "ar-DZ", - 0x3C01: "ar-BH", - 0x0C01: "ar", - 0x0801: "ar-IQ", - 0x2C01: "ar-JO", - 0x3401: "ar-KW", - 0x3001: "ar-LB", - 0x1001: "ar-LY", - 0x1801: "ary", - 0x2001: "ar-OM", - 0x4001: "ar-QA", - 0x0401: "ar-SA", - 0x2801: "ar-SY", - 0x1C01: "aeb", - 0x3801: "ar-AE", - 0x2401: "ar-YE", - 0x042B: "hy", - 0x044D: "as", - 0x082C: "az-Cyrl", - 0x042C: "az", - 0x046D: "ba", - 0x042D: "eu", - 0x0423: "be", - 0x0845: "bn", - 0x0445: "bn-IN", - 0x201A: "bs-Cyrl", - 0x141A: "bs", - 0x047E: "br", - 0x0402: "bg", - 0x0403: "ca", - 0x0C04: "zh-HK", - 0x1404: "zh-MO", - 0x0804: "zh", - 0x1004: "zh-SG", - 0x0404: "zh-TW", - 0x0483: "co", - 0x041A: "hr", - 0x101A: "hr-BA", - 0x0405: "cs", - 0x0406: "da", - 0x048C: "prs", - 0x0465: "dv", - 0x0813: "nl-BE", - 0x0413: "nl", - 0x0C09: "en-AU", - 0x2809: "en-BZ", - 0x1009: "en-CA", - 0x2409: "en-029", - 0x4009: "en-IN", - 0x1809: "en-IE", - 0x2009: "en-JM", - 0x4409: "en-MY", - 0x1409: "en-NZ", - 0x3409: "en-PH", - 0x4809: "en-SG", - 0x1C09: "en-ZA", - 0x2C09: "en-TT", - 0x0809: "en-GB", - 0x0409: "en", - 0x3009: "en-ZW", - 0x0425: "et", - 0x0438: "fo", - 0x0464: "fil", - 0x040B: "fi", - 0x080C: "fr-BE", - 0x0C0C: "fr-CA", - 0x040C: "fr", - 0x140C: "fr-LU", - 0x180C: "fr-MC", - 0x100C: "fr-CH", - 0x0462: "fy", - 0x0456: "gl", - 0x0437: "ka", - 0x0C07: "de-AT", - 0x0407: "de", - 0x1407: "de-LI", - 0x1007: "de-LU", - 0x0807: "de-CH", - 0x0408: "el", - 0x046F: "kl", - 0x0447: "gu", - 0x0468: "ha", - 0x040D: "he", - 0x0439: "hi", - 0x040E: "hu", - 0x040F: "is", - 0x0470: "ig", - 0x0421: "id", - 0x045D: "iu", - 0x085D: "iu-Latn", - 0x083C: "ga", - 0x0434: "xh", - 0x0435: "zu", - 0x0410: "it", - 0x0810: "it-CH", - 0x0411: "ja", - 0x044B: "kn", - 0x043F: "kk", - 0x0453: "km", - 0x0486: "quc", - 0x0487: "rw", - 0x0441: "sw", - 0x0457: "kok", - 0x0412: "ko", - 0x0440: "ky", - 0x0454: "lo", - 0x0426: "lv", - 0x0427: "lt", - 0x082E: "dsb", - 0x046E: "lb", - 0x042F: "mk", - 0x083E: "ms-BN", - 0x043E: "ms", - 0x044C: "ml", - 0x043A: "mt", - 0x0481: "mi", - 0x047A: "arn", - 0x044E: "mr", - 0x047C: "moh", - 0x0450: "mn", - 0x0850: "mn-CN", - 0x0461: "ne", - 0x0414: "nb", - 0x0814: "nn", - 0x0482: "oc", - 0x0448: "or", - 0x0463: "ps", - 0x0415: "pl", - 0x0416: "pt", - 0x0816: "pt-PT", - 0x0446: "pa", - 0x046B: "qu-BO", - 0x086B: "qu-EC", - 0x0C6B: "qu", - 0x0418: "ro", - 0x0417: "rm", - 0x0419: "ru", - 0x243B: "smn", - 0x103B: "smj-NO", - 0x143B: "smj", - 0x0C3B: "se-FI", - 0x043B: "se", - 0x083B: "se-SE", - 0x203B: "sms", - 0x183B: "sma-NO", - 0x1C3B: "sms", - 0x044F: "sa", - 0x1C1A: "sr-Cyrl-BA", - 0x0C1A: "sr", - 0x181A: "sr-Latn-BA", - 0x081A: "sr-Latn", - 0x046C: "nso", - 0x0432: "tn", - 0x045B: "si", - 0x041B: "sk", - 0x0424: "sl", - 0x2C0A: "es-AR", - 0x400A: "es-BO", - 0x340A: "es-CL", - 0x240A: "es-CO", - 0x140A: "es-CR", - 0x1C0A: "es-DO", - 0x300A: "es-EC", - 0x440A: "es-SV", - 0x100A: "es-GT", - 0x480A: "es-HN", - 0x080A: "es-MX", - 0x4C0A: "es-NI", - 0x180A: "es-PA", - 0x3C0A: "es-PY", - 0x280A: "es-PE", - 0x500A: "es-PR", - # Microsoft has defined two different language codes for - # “Spanish with modern sorting” and “Spanish with traditional - # sorting”. This makes sense for collation APIs, and it would be - # possible to express this in BCP 47 language tags via Unicode - # extensions (eg., “es-u-co-trad” is “Spanish with traditional - # sorting”). However, for storing names in fonts, this distinction - # does not make sense, so we use “es” in both cases. - 0x0C0A: "es", - 0x040A: "es", - 0x540A: "es-US", - 0x380A: "es-UY", - 0x200A: "es-VE", - 0x081D: "sv-FI", - 0x041D: "sv", - 0x045A: "syr", - 0x0428: "tg", - 0x085F: "tzm", - 0x0449: "ta", - 0x0444: "tt", - 0x044A: "te", - 0x041E: "th", - 0x0451: "bo", - 0x041F: "tr", - 0x0442: "tk", - 0x0480: "ug", - 0x0422: "uk", - 0x042E: "hsb", - 0x0420: "ur", - 0x0843: "uz-Cyrl", - 0x0443: "uz", - 0x042A: "vi", - 0x0452: "cy", - 0x0488: "wo", - 0x0485: "sah", - 0x0478: "ii", - 0x046A: "yo", -} - - -_MAC_LANGUAGES = { - 0: "en", - 1: "fr", - 2: "de", - 3: "it", - 4: "nl", - 5: "sv", - 6: "es", - 7: "da", - 8: "pt", - 9: "no", - 10: "he", - 11: "ja", - 12: "ar", - 13: "fi", - 14: "el", - 15: "is", - 16: "mt", - 17: "tr", - 18: "hr", - 19: "zh-Hant", - 20: "ur", - 21: "hi", - 22: "th", - 23: "ko", - 24: "lt", - 25: "pl", - 26: "hu", - 27: "es", - 28: "lv", - 29: "se", - 30: "fo", - 31: "fa", - 32: "ru", - 33: "zh", - 34: "nl-BE", - 35: "ga", - 36: "sq", - 37: "ro", - 38: "cz", - 39: "sk", - 40: "sl", - 41: "yi", - 42: "sr", - 43: "mk", - 44: "bg", - 45: "uk", - 46: "be", - 47: "uz", - 48: "kk", - 49: "az-Cyrl", - 50: "az-Arab", - 51: "hy", - 52: "ka", - 53: "mo", - 54: "ky", - 55: "tg", - 56: "tk", - 57: "mn-CN", - 58: "mn", - 59: "ps", - 60: "ks", - 61: "ku", - 62: "sd", - 63: "bo", - 64: "ne", - 65: "sa", - 66: "mr", - 67: "bn", - 68: "as", - 69: "gu", - 70: "pa", - 71: "or", - 72: "ml", - 73: "kn", - 74: "ta", - 75: "te", - 76: "si", - 77: "my", - 78: "km", - 79: "lo", - 80: "vi", - 81: "id", - 82: "tl", - 83: "ms", - 84: "ms-Arab", - 85: "am", - 86: "ti", - 87: "om", - 88: "so", - 89: "sw", - 90: "rw", - 91: "rn", - 92: "ny", - 93: "mg", - 94: "eo", - 128: "cy", - 129: "eu", - 130: "ca", - 131: "la", - 132: "qu", - 133: "gn", - 134: "ay", - 135: "tt", - 136: "ug", - 137: "dz", - 138: "jv", - 139: "su", - 140: "gl", - 141: "af", - 142: "br", - 143: "iu", - 144: "gd", - 145: "gv", - 146: "ga", - 147: "to", - 148: "el-polyton", - 149: "kl", - 150: "az", - 151: "nn", -} - - -_WINDOWS_LANGUAGE_CODES = { - lang.lower(): code for code, lang in _WINDOWS_LANGUAGES.items() -} -_MAC_LANGUAGE_CODES = {lang.lower(): code for code, lang in _MAC_LANGUAGES.items()} - - -# MacOS language ID → MacOS script ID -# -# Note that the script ID is not sufficient to determine what encoding -# to use in TrueType files. For some languages, MacOS used a modification -# of a mainstream script. For example, an Icelandic name would be stored -# with smRoman in the TrueType naming table, but the actual encoding -# is a special Icelandic version of the normal Macintosh Roman encoding. -# As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal -# Syllables but MacOS had run out of available script codes, so this was -# done as a (pretty radical) “modification” of Ethiopic. -# -# http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt -_MAC_LANGUAGE_TO_SCRIPT = { - 0: 0, # langEnglish → smRoman - 1: 0, # langFrench → smRoman - 2: 0, # langGerman → smRoman - 3: 0, # langItalian → smRoman - 4: 0, # langDutch → smRoman - 5: 0, # langSwedish → smRoman - 6: 0, # langSpanish → smRoman - 7: 0, # langDanish → smRoman - 8: 0, # langPortuguese → smRoman - 9: 0, # langNorwegian → smRoman - 10: 5, # langHebrew → smHebrew - 11: 1, # langJapanese → smJapanese - 12: 4, # langArabic → smArabic - 13: 0, # langFinnish → smRoman - 14: 6, # langGreek → smGreek - 15: 0, # langIcelandic → smRoman (modified) - 16: 0, # langMaltese → smRoman - 17: 0, # langTurkish → smRoman (modified) - 18: 0, # langCroatian → smRoman (modified) - 19: 2, # langTradChinese → smTradChinese - 20: 4, # langUrdu → smArabic - 21: 9, # langHindi → smDevanagari - 22: 21, # langThai → smThai - 23: 3, # langKorean → smKorean - 24: 29, # langLithuanian → smCentralEuroRoman - 25: 29, # langPolish → smCentralEuroRoman - 26: 29, # langHungarian → smCentralEuroRoman - 27: 29, # langEstonian → smCentralEuroRoman - 28: 29, # langLatvian → smCentralEuroRoman - 29: 0, # langSami → smRoman - 30: 0, # langFaroese → smRoman (modified) - 31: 4, # langFarsi → smArabic (modified) - 32: 7, # langRussian → smCyrillic - 33: 25, # langSimpChinese → smSimpChinese - 34: 0, # langFlemish → smRoman - 35: 0, # langIrishGaelic → smRoman (modified) - 36: 0, # langAlbanian → smRoman - 37: 0, # langRomanian → smRoman (modified) - 38: 29, # langCzech → smCentralEuroRoman - 39: 29, # langSlovak → smCentralEuroRoman - 40: 0, # langSlovenian → smRoman (modified) - 41: 5, # langYiddish → smHebrew - 42: 7, # langSerbian → smCyrillic - 43: 7, # langMacedonian → smCyrillic - 44: 7, # langBulgarian → smCyrillic - 45: 7, # langUkrainian → smCyrillic (modified) - 46: 7, # langByelorussian → smCyrillic - 47: 7, # langUzbek → smCyrillic - 48: 7, # langKazakh → smCyrillic - 49: 7, # langAzerbaijani → smCyrillic - 50: 4, # langAzerbaijanAr → smArabic - 51: 24, # langArmenian → smArmenian - 52: 23, # langGeorgian → smGeorgian - 53: 7, # langMoldavian → smCyrillic - 54: 7, # langKirghiz → smCyrillic - 55: 7, # langTajiki → smCyrillic - 56: 7, # langTurkmen → smCyrillic - 57: 27, # langMongolian → smMongolian - 58: 7, # langMongolianCyr → smCyrillic - 59: 4, # langPashto → smArabic - 60: 4, # langKurdish → smArabic - 61: 4, # langKashmiri → smArabic - 62: 4, # langSindhi → smArabic - 63: 26, # langTibetan → smTibetan - 64: 9, # langNepali → smDevanagari - 65: 9, # langSanskrit → smDevanagari - 66: 9, # langMarathi → smDevanagari - 67: 13, # langBengali → smBengali - 68: 13, # langAssamese → smBengali - 69: 11, # langGujarati → smGujarati - 70: 10, # langPunjabi → smGurmukhi - 71: 12, # langOriya → smOriya - 72: 17, # langMalayalam → smMalayalam - 73: 16, # langKannada → smKannada - 74: 14, # langTamil → smTamil - 75: 15, # langTelugu → smTelugu - 76: 18, # langSinhalese → smSinhalese - 77: 19, # langBurmese → smBurmese - 78: 20, # langKhmer → smKhmer - 79: 22, # langLao → smLao - 80: 30, # langVietnamese → smVietnamese - 81: 0, # langIndonesian → smRoman - 82: 0, # langTagalog → smRoman - 83: 0, # langMalayRoman → smRoman - 84: 4, # langMalayArabic → smArabic - 85: 28, # langAmharic → smEthiopic - 86: 28, # langTigrinya → smEthiopic - 87: 28, # langOromo → smEthiopic - 88: 0, # langSomali → smRoman - 89: 0, # langSwahili → smRoman - 90: 0, # langKinyarwanda → smRoman - 91: 0, # langRundi → smRoman - 92: 0, # langNyanja → smRoman - 93: 0, # langMalagasy → smRoman - 94: 0, # langEsperanto → smRoman - 128: 0, # langWelsh → smRoman (modified) - 129: 0, # langBasque → smRoman - 130: 0, # langCatalan → smRoman - 131: 0, # langLatin → smRoman - 132: 0, # langQuechua → smRoman - 133: 0, # langGuarani → smRoman - 134: 0, # langAymara → smRoman - 135: 7, # langTatar → smCyrillic - 136: 4, # langUighur → smArabic - 137: 26, # langDzongkha → smTibetan - 138: 0, # langJavaneseRom → smRoman - 139: 0, # langSundaneseRom → smRoman - 140: 0, # langGalician → smRoman - 141: 0, # langAfrikaans → smRoman - 142: 0, # langBreton → smRoman (modified) - 143: 28, # langInuktitut → smEthiopic (modified) - 144: 0, # langScottishGaelic → smRoman (modified) - 145: 0, # langManxGaelic → smRoman (modified) - 146: 0, # langIrishGaelicScript → smRoman (modified) - 147: 0, # langTongan → smRoman - 148: 6, # langGreekAncient → smRoman - 149: 0, # langGreenlandic → smRoman - 150: 0, # langAzerbaijanRoman → smRoman - 151: 0, # langNynorsk → smRoman -} - - -class NameRecordVisitor(TTVisitor): - # Font tables that have NameIDs we need to collect. - TABLES = ("GSUB", "GPOS", "fvar", "CPAL", "STAT") - - def __init__(self): - self.seen = set() - - -@NameRecordVisitor.register_attrs( - ( - (otTables.FeatureParamsSize, ("SubfamilyID", "SubfamilyNameID")), - (otTables.FeatureParamsStylisticSet, ("UINameID",)), - ( - otTables.FeatureParamsCharacterVariants, - ( - "FeatUILabelNameID", - "FeatUITooltipTextNameID", - "SampleTextNameID", - "FirstParamUILabelNameID", - ), - ), - (otTables.STAT, ("ElidedFallbackNameID",)), - (otTables.AxisRecord, ("AxisNameID",)), - (otTables.AxisValue, ("ValueNameID",)), - (otTables.FeatureName, ("FeatureNameID",)), - (otTables.Setting, ("SettingNameID",)), - ) -) -def visit(visitor, obj, attr, value): - visitor.seen.add(value) - - -@NameRecordVisitor.register(ttLib.getTableClass("fvar")) -def visit(visitor, obj): - for inst in obj.instances: - if inst.postscriptNameID != 0xFFFF: - visitor.seen.add(inst.postscriptNameID) - visitor.seen.add(inst.subfamilyNameID) - - for axis in obj.axes: - visitor.seen.add(axis.axisNameID) - - -@NameRecordVisitor.register(ttLib.getTableClass("CPAL")) -def visit(visitor, obj): - if obj.version == 1: - visitor.seen.update(obj.paletteLabels) - visitor.seen.update(obj.paletteEntryLabels) - - -@NameRecordVisitor.register(ttLib.TTFont) -def visit(visitor, font, *args, **kwargs): - if hasattr(visitor, "font"): - return False - - visitor.font = font - for tag in visitor.TABLES: - if tag in font: - visitor.visit(font[tag], *args, **kwargs) - del visitor.font - return False diff --git a/spaces/codelion/Grounding_DINO_demo/groundingdino/util/__init__.py b/spaces/codelion/Grounding_DINO_demo/groundingdino/util/__init__.py deleted file mode 100644 index 168f9979a4623806934b0ff1102ac166704e7dec..0000000000000000000000000000000000000000 --- a/spaces/codelion/Grounding_DINO_demo/groundingdino/util/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved diff --git a/spaces/codeparrot/code-generation-models/utils/intro.md b/spaces/codeparrot/code-generation-models/utils/intro.md deleted file mode 100644 index 1d575efdfded501e9ea120781e2910c71787d083..0000000000000000000000000000000000000000 --- a/spaces/codeparrot/code-generation-models/utils/intro.md +++ /dev/null @@ -1,9 +0,0 @@ -## Introduction - -The application of language models to code generation has sparked great interest recently. You have probably heard of [Codex](https://arxiv.org/pdf/2107.03374v2.pdf), the model behind [Github Copilot](https://copilot.github.com/), or [AlphaCode](https://www.deepmind.com/blog/competitive-programming-with-alphacode) for competition-level programming. These models aren't open-source, and it is hard to reproduce them with a limited budget and incomplete information about their training. The ML community has luckily contributed some code models to allow for further research. - -However, it can be easy to get lost between models. At Hugging Face we aim to democratize ML and centralize all information in the 🤗 ecosystem to make the usage of open-source tools easier and more efficient. Code models aren't an exception, you can find all open-source models on the Hub, with several code datasets and evaluation metrics. In this blog we will give an overview of these tools and how to use them. - -

- drawing -

\ No newline at end of file diff --git "a/spaces/codertoro/gpt-academic/crazy_functions/Latex\345\205\250\346\226\207\347\277\273\350\257\221.py" "b/spaces/codertoro/gpt-academic/crazy_functions/Latex\345\205\250\346\226\207\347\277\273\350\257\221.py" deleted file mode 100644 index c1684b31b93640f9ad77d0c44cefd47ae1262ad7..0000000000000000000000000000000000000000 --- "a/spaces/codertoro/gpt-academic/crazy_functions/Latex\345\205\250\346\226\207\347\277\273\350\257\221.py" +++ /dev/null @@ -1,176 +0,0 @@ -from toolbox import update_ui -from toolbox import CatchException, report_execption, write_results_to_file -fast_debug = False - -class PaperFileGroup(): - def __init__(self): - self.file_paths = [] - self.file_contents = [] - self.sp_file_contents = [] - self.sp_file_index = [] - self.sp_file_tag = [] - - # count_token - import tiktoken - from toolbox import get_conf - enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL')) - def get_token_num(txt): return len(enc.encode(txt)) - self.get_token_num = get_token_num - - def run_file_split(self, max_token_limit=1900): - """ - 将长文本分离开来 - """ - for index, file_content in enumerate(self.file_contents): - if self.get_token_num(file_content) < max_token_limit: - self.sp_file_contents.append(file_content) - self.sp_file_index.append(index) - self.sp_file_tag.append(self.file_paths[index]) - else: - from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf - segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit) - for j, segment in enumerate(segments): - self.sp_file_contents.append(segment) - self.sp_file_index.append(index) - self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.tex") - - print('Segmentation: done') - -def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'): - import time, os, re - from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency - - # <-------- 读取Latex文件,删除其中的所有注释 ----------> - pfg = PaperFileGroup() - - for index, fp in enumerate(file_manifest): - with open(fp, 'r', encoding='utf-8') as f: - file_content = f.read() - # 定义注释的正则表达式 - comment_pattern = r'%.*' - # 使用正则表达式查找注释,并替换为空字符串 - clean_tex_content = re.sub(comment_pattern, '', file_content) - # 记录删除注释后的文本 - pfg.file_paths.append(fp) - pfg.file_contents.append(clean_tex_content) - - # <-------- 拆分过长的latex文件 ----------> - pfg.run_file_split(max_token_limit=1024) - n_split = len(pfg.sp_file_contents) - - # <-------- 抽取摘要 ----------> - # if language == 'en': - # abs_extract_inputs = f"Please write an abstract for this paper" - - # # 单线,获取文章meta信息 - # paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive( - # inputs=abs_extract_inputs, - # inputs_show_user=f"正在抽取摘要信息。", - # llm_kwargs=llm_kwargs, - # chatbot=chatbot, history=[], - # sys_prompt="Your job is to collect information from materials。", - # ) - - # <-------- 多线程润色开始 ----------> - if language == 'en->zh': - inputs_array = ["Below is a section from an English academic paper, translate it into Chinese, do not modify any latex command such as \section, \cite and equations:" + - f"\n\n{frag}" for frag in pfg.sp_file_contents] - inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag] - sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)] - elif language == 'zh->en': - inputs_array = [f"Below is a section from a Chinese academic paper, translate it into English, do not modify any latex command such as \section, \cite and equations:" + - f"\n\n{frag}" for frag in pfg.sp_file_contents] - inputs_show_user_array = [f"润色 {f}" for f in pfg.sp_file_tag] - sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)] - - gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( - inputs_array=inputs_array, - inputs_show_user_array=inputs_show_user_array, - llm_kwargs=llm_kwargs, - chatbot=chatbot, - history_array=[[""] for _ in range(n_split)], - sys_prompt_array=sys_prompt_array, - max_workers=10, # OpenAI所允许的最大并行过载 - scroller_max_len = 80 - ) - - # <-------- 整理结果,退出 ----------> - create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md" - res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name) - history = gpt_response_collection - chatbot.append((f"{fp}完成了吗?", res)) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - - - - -@CatchException -def Latex英译中(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - # 基本信息:功能、贡献者 - chatbot.append([ - "函数插件功能?", - "对整个Latex项目进行翻译。函数插件贡献者: Binary-Husky"]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 尝试导入依赖,如果缺少依赖,则给出安装建议 - try: - import tiktoken - except: - report_execption(chatbot, history, - a=f"解析项目: {txt}", - b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - history = [] # 清空历史,以免输入溢出 - import glob, os - if os.path.exists(txt): - project_folder = txt - else: - if txt == "": txt = '空空如也的输入栏' - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] - if len(file_manifest) == 0: - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en->zh') - - - - - -@CatchException -def Latex中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - # 基本信息:功能、贡献者 - chatbot.append([ - "函数插件功能?", - "对整个Latex项目进行翻译。函数插件贡献者: Binary-Husky"]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 尝试导入依赖,如果缺少依赖,则给出安装建议 - try: - import tiktoken - except: - report_execption(chatbot, history, - a=f"解析项目: {txt}", - b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - history = [] # 清空历史,以免输入溢出 - import glob, os - if os.path.exists(txt): - project_folder = txt - else: - if txt == "": txt = '空空如也的输入栏' - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] - if len(file_manifest) == 0: - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh->en') \ No newline at end of file diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dump_extradata_bsf.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dump_extradata_bsf.c deleted file mode 100644 index 5506d5ed6564dcd5ab1da4812ad773f82b63e7db..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dump_extradata_bsf.c +++ /dev/null @@ -1,106 +0,0 @@ -/* - * copyright (c) 2006 Michael Niedermayer - * - * 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 "bsf.h" -#include "bsf_internal.h" - -#include "libavutil/log.h" -#include "libavutil/opt.h" - -enum DumpFreq { - DUMP_FREQ_KEYFRAME, - DUMP_FREQ_ALL, -}; - -typedef struct DumpExtradataContext { - const AVClass *class; - AVPacket pkt; - int freq; -} DumpExtradataContext; - -static int dump_extradata(AVBSFContext *ctx, AVPacket *out) -{ - DumpExtradataContext *s = ctx->priv_data; - AVPacket *in = &s->pkt; - int ret = 0; - - ret = ff_bsf_get_packet_ref(ctx, in); - if (ret < 0) - return ret; - - if (ctx->par_in->extradata && - (s->freq == DUMP_FREQ_ALL || - (s->freq == DUMP_FREQ_KEYFRAME && in->flags & AV_PKT_FLAG_KEY)) && - (in->size < ctx->par_in->extradata_size || - memcmp(in->data, ctx->par_in->extradata, ctx->par_in->extradata_size))) { - if (in->size >= INT_MAX - ctx->par_in->extradata_size) { - ret = AVERROR(ERANGE); - goto fail; - } - - ret = av_new_packet(out, in->size + ctx->par_in->extradata_size); - if (ret < 0) - goto fail; - - ret = av_packet_copy_props(out, in); - if (ret < 0) { - av_packet_unref(out); - goto fail; - } - - memcpy(out->data, ctx->par_in->extradata, ctx->par_in->extradata_size); - memcpy(out->data + ctx->par_in->extradata_size, in->data, in->size); - } else { - av_packet_move_ref(out, in); - } - -fail: - av_packet_unref(in); - - return ret; -} - -#define OFFSET(x) offsetof(DumpExtradataContext, x) -#define FLAGS (AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_BSF_PARAM) -static const AVOption options[] = { - { "freq", "When to dump extradata", OFFSET(freq), AV_OPT_TYPE_INT, - { .i64 = DUMP_FREQ_KEYFRAME }, DUMP_FREQ_KEYFRAME, DUMP_FREQ_ALL, FLAGS, "freq" }, - { "k", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = DUMP_FREQ_KEYFRAME }, .flags = FLAGS, .unit = "freq" }, - { "keyframe", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = DUMP_FREQ_KEYFRAME }, .flags = FLAGS, .unit = "freq" }, - { "e", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = DUMP_FREQ_ALL }, .flags = FLAGS, .unit = "freq" }, - { "all", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = DUMP_FREQ_ALL }, .flags = FLAGS, .unit = "freq" }, - { NULL }, -}; - -static const AVClass dump_extradata_class = { - .class_name = "dump_extradata bsf", - .item_name = av_default_item_name, - .option = options, - .version = LIBAVUTIL_VERSION_INT, -}; - -const FFBitStreamFilter ff_dump_extradata_bsf = { - .p.name = "dump_extra", - .p.priv_class = &dump_extradata_class, - .priv_data_size = sizeof(DumpExtradataContext), - .filter = dump_extradata, -}; diff --git a/spaces/congsaPfin/Manga-OCR/logs/Catch Them All with PGSharp Spoofer Pokemon Go APK for Android.md b/spaces/congsaPfin/Manga-OCR/logs/Catch Them All with PGSharp Spoofer Pokemon Go APK for Android.md deleted file mode 100644 index 57202efd2c1a015ebc6f6d273b209bc3517022bc..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Catch Them All with PGSharp Spoofer Pokemon Go APK for Android.md +++ /dev/null @@ -1,131 +0,0 @@ -
-

Spoofer Pokemon Go APK: How to Spoof Your Location Safely and Effectively

-

Pokemon Go is an augmented reality game that requires you to physically travel to different locations to catch Pokemon, visit Pokestops, enter gyms, and explore the world. However, not everyone has the time, money, or opportunity to do so. That's why some players resort to spoofing, which is the act of tricking your phone's GPS into processing another location in the world.

-

spoofer pokemon go apk


Download Filehttps://urlca.com/2uO87G



-

Spoofing can help you catch rare and regional Pokemon that you would normally not have access to. It can also help you complete research tasks faster, take over more gyms easier, and enjoy the game from the comfort of your home. However, spoofing also comes with some risks and challenges that you should be aware of before trying it.

-

In this article, we will provide you with some information and tips on how to spoof Pokemon Go safely and effectively. We will explain how to use a VPN or a GPS spoofing app to change your location in the game. We will also recommend some of the best options for spoofing tools and provide some useful advice for spoofing.

-

How to Spoof Pokemon Go with a VPN?

-

A VPN (Virtual Private Network) is a service that encrypts your internet traffic and routes it through a server in another location. This way, you can hide your real IP address and appear as if you are accessing the internet from somewhere else. You can use a VPN to spoof your location for Pokemon Go by following these steps:

-
    -
  1. Determine which VPN service will best meet your needs. In this case, we'll use NordVPN as an example.
  2. -
  3. Download and install NordVPN on your device.
  4. -
  5. Launch NordVPN and choose a location you want to play Pokemon Go in. For example, if you want to catch Kangaskhan in Australia, you can select an Australian server.
  6. -
  7. Launch Pokemon Go. You can now play the game with your new, spoofed location.
  8. -
-

A VPN can help you spoof your location for Pokemon Go without rooting your device or installing any additional apps. It can also protect your online privacy and security by encrypting your data and preventing anyone

How to Spoof Pokemon Go with a GPS Spoofing App?

-

A GPS spoofing app is an application that allows you to fake your location by overriding your phone's GPS signal. You can use a GPS spoofing app to spoof your location for Pokemon Go by following these steps:

-
    -
  1. Find a GPS spoofing app that works for your device. In this case, we'll use PGSharp as an example.
  2. -
  3. Download and install PGSharp on your device. You may need to enable unknown sources or disable Google Play Protect to install it.
  4. -
  5. Launch PGSharp and grant it the necessary permissions to access your location and storage.
  6. -
  7. Select a location you want to play Pokemon Go in. You can use the map, the search bar, or the coordinates to find a place.
  8. -
  9. Tap on the Start button to activate the spoofing mode. You will see a joystick and some buttons on your screen.
  10. -
  11. Launch Pokemon Go. You can now play the game with your new, spoofed location.
  12. -
-

A GPS spoofing app can help you spoof your location for Pokemon Go without using a VPN or changing your device settings. It can also give you more control over your movement and speed in the game. However, it may not work on all devices or Android versions, and it may require you to uninstall or disable some apps or features on your device.

-

What are the Best VPNs and GPS Spoofing Apps for Pokemon Go?

-

There are many VPNs and GPS spoofing apps available for spoofing Pokemon Go, but not all of them are reliable, safe, or effective. Some of them may not work well with the game, some of them may contain malware or viruses, and some of them may be detected and banned by Niantic. Therefore, you should be careful when choosing a spoofing tool for Pokemon Go. Here are some of the best options for VPNs and GPS spoofing apps for Pokemon Go:

-

PGSharp - Pokémon GO Spoofer APK
-Pokémon GO Hack PGSharp for Android
-Smali Patcher Pokémon GO Spoofing App
-Pokémon GO Spoofer iMoveGo for iOS and Android
-PGSharp APK Download for Android - Softonic
-PGSharp APK (Android Game) - Free Download - APKCombo
-2023 Most Popular Pokémon GO Spoofers On Android or iOS - WooTechy
-How to Spoof Pokémon GO Location on Android with PGSharp
-PGSharp - The Best Pokémon GO Spoofing App No Root 2023
-PGSharp APK Latest Version 1.100.1 for Android - APKFab
-How to Install PGSharp APK on Android Devices - TechBigs
-PGSharp: The Ultimate Guide to Pokémon GO Spoofing in 2023
-Best Pokémon GO Spoofer Apps for iOS and Android in 2023
-How to Use Smali Patcher to Spoof Pokémon GO Location on Android
-iMoveGo: The Easiest Way to Spoof Pokémon GO Location on iOS and Android
-PGSharp APK Mod Menu for Pokémon GO (Unlimited Coins)
-How to Download and Install PGSharp APK on PC - Windows and Mac
-PGSharp Alternatives: Top 10 Pokémon GO Spoofer Apps for Android and iOS
-How to Fix PGSharp Not Working Issues on Pokémon GO
-PGSharp Review: Is It Safe and Reliable to Spoof Pokémon GO Location?
-How to Get PGSharp Key for Free in 2023 - Pokémon GO Spoofer
-How to Update PGSharp APK to the Latest Version of Pokémon GO
-How to Uninstall PGSharp APK from Your Android Device
-How to Use PGSharp Features: Joystick, Teleport, Auto Walk, and More
-How to Avoid Getting Banned When Using PGSharp or Other Pokémon GO Spoofer Apps
-How to Spoof Pokémon GO Location on iOS with iSpoofer or iTools
-How to Spoof Pokémon GO Location on Android with Fake GPS or FGL Pro
-How to Spoof Pokémon GO Location on PC with BlueStacks or Nox Player
-How to Spoof Pokémon GO Location on Mac with Xcode or Simulator
-How to Spoof Pokémon GO Location on Chromebook with ARC Welder or Developer Mode
-How to Use Cooldown Rule for Any Pokémon GO Spoofing Apps
-How to Catch Rare and Legendary Pokémon with PGSharp or Other Spoofer Apps
-How to Join Raids and Battles with PGSharp or Other Spoofer Apps
-How to Hatch Eggs Faster with PGSharp or Other Spoofer Apps
-How to Find 100 IV Pokémon with PGSharp or Other Spoofer Apps
-How to Use Nearby Radar and Enhanced Throw Features in PGSharp
-How to Use Quick Catch and Quick Load Map Features in PGSharp
-How to Use Block Non-Shiny and Skip Evolve Animations Features in PGSharp
-How to Use Go Plus Compatibility Feature in PGSharp
-How to Use Encounter/Inventory IV and Caught Preview Features in PGSharp
-How to Use Favorites and Routes Features in PGSharp
-How to Use Save Last Location and Restore Last Location Features in PGSharp
-How to Change Walking Speed and Movement Mode in PGSharp
-How to Enable or Disable Mock Locations in Developer Options for PGSharp
-How to Enable or Disable Root Mode in Settings for Smali Patcher

- - - - - - - - - - - - - - - - - - - - - - - - - -
VPNGPS Spoofing App
NordVPNPGSharp
ExpressVPNSmali Patcher
SurfsharkFake GPS Location by Lexa
CyberGhostFake GPS GO Location Spoofer Free by IncorporateApps
PureVPNFGL Pro by LTP PRO LLC
-

NordVPN is one of the most popular and trusted VPN services in the world. It has over 5,000 servers in 60 countries, which means you can spoof your location to almost anywhere in the world. It also has fast speeds, strong encryption, and a strict no-logs policy. NordVPN works well with Pokemon Go and can bypass geo-restrictions and firewalls. It also offers a 30-day money-back guarantee and 24/7 customer support.

-

PGSharp is one of the most popular and easy-to-use GPS spoofing apps for Pokemon Go. It is a modified version of the official Pokemon Go app that has a built-in spoofing feature. You don't need to root your device or install any other apps to use it. You just need to download and install PGSharp on your device and select a location to play. PGSharp also has a joystick, a teleport feature, an enhanced throw feature, and an auto-walk feature that can enhance your gameplay.

-

ExpressVPN is another top-rated VPN service that offers fast, secure, and reliable spoofing for Pokemon Go. It has over 3,000 servers in 94 countries, which gives you plenty of options to choose from. It also has strong encryption, a kill switch, a split tunneling feature, and a no-logs policy. ExpressVPN can work with any device and any network, and it can unblock any website or app. It also offers a 30-day money-back guarantee and 24/7 customer support.

-

Smali Patcher is another powerful and effective GPS spoofing app for Pokemon Go. It is a tool that creates a module that can hide your mock location from the game. You need to root your device and install Magisk Manager to use it. You also need to connect your device to a PC and run Smali Patcher on it. Once you have created the module, you can install it on your device and use any mock location app to spoof your location.

-

The other VPNs and GPS spoofing apps listed above are also good choices for spoofing Pokemon Go, but they may have some drawbacks or limitations compared to NordVPN and PGSharp. For example, some of them may have slower speeds, fewer servers, weaker encryption, or more ads. You should do your own research and compare the features, prices, and reviews of each spoofing tool before deciding which one to use.

-

What are Some Tips and Tricks for Spoofing Pokemon Go?

-

Spoofing Pokemon Go can be fun and rewarding, but it can also be risky and challenging. If you are not careful, you may end up getting banned, losing your account, or facing legal consequences. You may also encounter some technical issues, such as errors, glitches, or crashes. Therefore, you should follow some tips and tricks for spoofing Pokemon Go safely and effectively. Here are some of them:

-
    -
  • Follow the cooldown rules. Cooldown is the time you need to wait before you can interact with the game after changing your location. If you ignore the cooldown rules, you may trigger a soft ban or a red warning. The cooldown time depends on the distance you travel, but it can range from 2 minutes to 2 hours. You can use a cooldown chart or calculator to find out how long you need to wait.
  • -
  • Avoid suspicious behavior. Niantic can detect and ban spoofers who act in ways that are unrealistic or impossible for normal players. For example, if you jump from one continent to another in a matter of minutes, or if you catch hundreds of Pokemon in a day, you may raise some red flags. You should try to spoof in a way that mimics how a real player would play the game.
  • -
  • Choose realistic locations. When spoofing your location, you should choose places that are plausible and consistent with your previous locations. For example, if you live in New York, you can spoof to nearby cities or states, but not to remote islands or countries. You should also avoid spoofing to locations that are known to be hotspots for spoofers, such as Paris Mall or Central Park.
  • -
  • Use common sense. Spoofing Pokemon Go is not a guarantee that you will catch all the Pokemon you want or achieve all your goals in the game. You still need to use some strategy, skill, and luck to play the game well. You should also respect the rules and the community of the game, and not abuse or exploit your spoofing advantage.
  • -
-

Conclusion

-

Spoofing Pokemon Go is a controversial and complicated topic that has both pros and cons. Spoofing can help you catch rare and regional Pokemon, complete research tasks faster, take over more gyms easier, and enjoy the game from the comfort of your home. However, spoofing also comes with some risks and challenges that you should be aware of before trying it.

-

You can spoof Pokemon Go by using a VPN or a GPS spoofing app to change your location in the game. You should choose a reliable and trustworthy spoofing tool that works well with the game and protects your online privacy and security. You should also follow some tips and tricks for spoofing safely and effectively.

-

If you want to try spoofing Pokemon Go at your own risk and discretion, we hope this article has provided you with some useful information and guidance. If you have any opinions or experiences with spoofing Pokemon Go, feel free to share them with us in the comments below.

-

FAQs

-

Here are some frequently asked questions about spoofing Pokemon Go:

-
    -
  1. Is spoofing Pokemon Go illegal?
  2. -

    Spoofing Pokemon Go is not illegal per se, but it may violate the terms of service of the game or the laws of some countries or regions. For example, in some places, using a VPN or a GPS spoofing app may be considered as cybercrime or fraud. You should check the local laws and regulations before spoofing Pokemon Go.

    -
  3. How can I avoid getting banned for spoofing Pokemon Go?
  4. -

    There is no foolproof way to avoid getting banned for spoofing Pokemon Go, as Niantic is constantly updating its anti-cheat system and detecting spoofers. However, you can reduce the chances of getting banned by following some precautions, such as using a reputable VPN or GPS spoofing app, following the cooldown rules, avoiding suspicious behavior, choosing realistic locations, etc.

    -
  5. Can I spoof Pokemon Go on iOS devices?
  6. -

    Yes, you can spoof Pokemon Go on iOS devices, but it may be more difficult and risky than on Android devices. You may need to jailbreak your device or use a third-party app store to install a modified version of Pokemon Go that has a built-in spoofing feature. However, these methods may expose your device to malware or viruses, or cause your device to malfunction.

    -
  7. < strong>Can I spoof Pokemon Go on PC?
  8. -

    Yes, you can spoof Pokemon Go on PC, but it may be more complicated and risky than on mobile devices. You may need to use an emulator or a virtual machine to run Pokemon Go on your PC. You may also need to use a VPN or a GPS spoofing app to change your location in the game. However, these methods may not work well with the game, or may be detected and banned by Niantic.

    -
  9. What are some of the best places to spoof Pokemon Go?
  10. -

    Some of the best places to spoof Pokemon Go are those that have a high density of Pokemon, Pokestops, gyms, and raids. Some examples are New York City, San Francisco, London, Tokyo, Paris, etc. However, you should also consider the availability and rarity of the Pokemon you want to catch, the time zone and weather of the location, and the popularity and safety of the location.

    -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Drive a Tesla in Car Parking Multiplayer with This Mod Apk.md b/spaces/congsaPfin/Manga-OCR/logs/Drive a Tesla in Car Parking Multiplayer with This Mod Apk.md deleted file mode 100644 index 7374c75e5b0fb2416023b1a457b2a347e4c10c42..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Drive a Tesla in Car Parking Multiplayer with This Mod Apk.md +++ /dev/null @@ -1,125 +0,0 @@ - -

Car Parking Multiplayer APK Tesla Mod: How to Download and Install It

-

Do you love playing car parking games on your Android device? Do you want to drive a Tesla car in a realistic and immersive environment? If yes, then you should try Car Parking Multiplayer APK Tesla Mod. This is a modified version of the popular game Car Parking Multiplayer that allows you to enjoy the features and benefits of a Tesla car in the game. In this article, we will tell you what Car Parking Multiplayer is, what Tesla Mod is, how to download and install it, and how to use it in the game. Let's get started!

-

What is Car Parking Multiplayer?

-

Car Parking Multiplayer is a simulation game that lets you experience the thrill and challenge of parking different types of cars in various scenarios. You can choose from over 100 cars, including sedans, sports cars, trucks, buses, and more. You can also customize your car with different colors, wheels, stickers, and accessories. You can play in single-player mode or multiplayer mode, where you can interact with other players online. You can chat with them, join races, exchange cars, or even prank them. You can also explore different maps, such as city, airport, desert, port, and more. You can follow the traffic rules or break them, depending on your mood. You can also use different camera angles to get a better view of your car and the surroundings.

-

car parking multiplayer apk tesla mod


Download Zip ->>->>->> https://urlca.com/2uO4Bt



-

Features of Car Parking Multiplayer

-

Some of the features of Car Parking Multiplayer are:

-
    -
  • Realistic car physics and sound effects
  • -
  • Free roam mode and parking mode
  • -
  • Over 100 cars to choose from
  • -
  • Car customization and tuning
  • -
  • Multiplayer mode with voice chat
  • -
  • Different maps and environments
  • -
  • Traffic system and police mode
  • -
  • Day and night cycle and weather effects
  • -
  • In-game currency and rewards
  • -
-

How to play Car Parking Multiplayer

-

To play Car Parking Multiplayer, you need to download and install the game from the Google Play Store or from any other trusted source. Once you launch the game, you can choose your preferred language and sign in with your Google account or Facebook account. You can also play as a guest if you don't want to sign in. Then, you can select your car from the garage and customize it as you like. You can also buy new cars with the money you earn in the game. Next, you can choose the map you want to play in and the mode you want to play. You can either play in free roam mode or parking mode. In free roam mode, you can drive around the map and explore different places. In parking mode, you have to park your car in the designated spot without hitting any obstacles or other cars. You have to follow the arrows on the road to find your parking spot. You can also switch between different camera angles to get a better view of your car and the surroundings.

-

What is Tesla Mod?

-

Tesla Mod is a modified version of Car Parking Multiplayer that adds a Tesla car to the game. Tesla is a famous brand of electric cars that are known for their high performance, innovation, and eco-friendliness. Tesla cars have many advanced features, such as self-driving mode, autopilot mode, smart summon mode, sentry mode, and more. Tesla Mod allows you to enjoy these features in Car Parking Multiplayer. You can drive a Tesla car in the game and use its special functions to enhance your gameplay experience.

-

Benefits of Tesla Mod

-

Some of the benefits of Tesla Mod are:

    -
  • Access to a Tesla car in the game
  • -
  • Ability to use self-driving mode, autopilot mode, smart summon mode, sentry mode, and more
  • -
  • Improved performance, speed, and handling of the car
  • -
  • Reduced fuel consumption and emissions
  • -
  • Enhanced entertainment and gaming options
  • -
-

How to download and install Tesla Mod

-

To download and install Tesla Mod, you need to follow these steps:

-
    -
  1. Download the Tesla Mod APK file from a reliable source. You can search for it online or use this link. Make sure you have enough storage space on your device.
  2. -
  3. Enable the installation of unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on.
  4. -
  5. Locate the downloaded APK file on your device and tap on it to start the installation process. Follow the instructions on the screen and wait for the installation to complete.
  6. -
  7. Launch the Tesla Mod app and grant the necessary permissions. You will see a Tesla logo on the app icon.
  8. -
  9. Enjoy the Tesla Mod features in Car Parking Multiplayer.
  10. -
-

How to use Tesla Mod in Car Parking Multiplayer

-

Once you have installed Tesla Mod, you can use it in Car Parking Multiplayer by following these steps:

-
    -
  1. Select your Tesla car from the garage. You can choose from different models, such as Model S, Model 3, Model X, Model Y, Cybertruck, Roadster, and more.
  2. -
  3. Customize your Tesla car as you like. You can change the color, wheels, stickers, accessories, and more. You can also tune your car for better performance.
  4. -
  5. Select the map and mode you want to play in. You can play in free roam mode or parking mode.
  6. -
  7. Drive your Tesla car and use its special features. You can activate self-driving mode by tapping on the steering wheel icon on the screen. You can also use autopilot mode, smart summon mode, sentry mode, and more by tapping on the corresponding icons on the screen. You can also switch between different camera angles to get a better view of your car and the surroundings.
  8. -
-

Tips and tricks for using Tesla Mod

-

Some of the tips and tricks for using Tesla Mod are:

-

car parking multiplayer mod apk unlimited money tesla
-download car parking multiplayer tesla mod apk free
-car parking multiplayer hack apk tesla cybertruck
-how to install car parking multiplayer tesla mod apk
-car parking multiplayer mod apk latest version tesla
-car parking multiplayer online tesla mod apk android
-car parking multiplayer tesla roadster mod apk
-car parking multiplayer mod menu apk tesla
-car parking multiplayer 3d tesla mod apk
-car parking multiplayer simulator tesla mod apk
-car parking multiplayer cheats apk tesla model 3
-car parking multiplayer premium apk tesla model s
-car parking multiplayer realistic tesla mod apk
-car parking multiplayer sandbox tesla mod apk
-car parking multiplayer drift tesla mod apk
-car parking multiplayer custom tesla mod apk
-car parking multiplayer unlocked tesla mod apk
-car parking multiplayer update tesla mod apk
-car parking multiplayer offline tesla mod apk
-car parking multiplayer fun tesla mod apk
-car parking multiplayer new tesla mod apk
-car parking multiplayer best tesla mod apk
-car parking multiplayer easy tesla mod apk
-car parking multiplayer hard tesla mod apk
-car parking multiplayer crazy tesla mod apk
-car parking multiplayer pro tesla mod apk
-car parking multiplayer classic tesla mod apk
-car parking multiplayer modern tesla mod apk
-car parking multiplayer fast tesla mod apk
-car parking multiplayer slow tesla mod apk
-car parking multiplayer smooth tesla mod apk
-car parking multiplayer glitchy tesla mod apk
-car parking multiplayer awesome tesla mod apk
-car parking multiplayer cool tesla mod apk
-car parking multiplayer amazing tesla mod apk
-car parking multiplayer epic tesla mod apk
-car parking multiplayer legendary tesla mod apk
-car parking multiplayer rare tesla mod apk
-car parking multiplayer exclusive tesla mod apk
-car parking multiplayer special tesla mod apk

-
    -
  • Use self-driving mode when you want to relax and enjoy the scenery. The car will drive itself and follow the traffic rules. You can also adjust the speed and distance of the car by using the slider on the screen.
  • -
  • Use autopilot mode when you want to drive faster and more efficiently. The car will automatically change lanes, overtake other cars, and avoid obstacles. You can also use voice commands to control the car by tapping on the microphone icon on the screen.
  • -
  • Use smart summon mode when you want to call your car to your location. The car will navigate itself to where you are standing. You can also use this feature to park your car remotely by tapping on the parking icon on the screen.
  • -
  • Use sentry mode when you want to protect your car from theft or vandalism. The car will monitor its surroundings and alert you if it detects any threat. It will also record video footage of any incident and upload it to your cloud account.
  • -
  • Use entertainment and gaming options when you want to have fun in your car. You can watch YouTube, Netflix, Hulu, or other streaming services by tapping on the theater icon on the screen. You can also play video games like Fallout Shelter, Cuphead, Beach Buggy Racing 2, or other arcade games by tapping on the arcade icon on the screen.
  • -
-

Precautions and risks of using Tesla Mod

-

Some of the precautions and risks of using Tesla Mod are:

-
    -
  • Tesla Mod is not an official app from Tesla or Car Parking Multiplayer developers. It is a third-party app that may contain malware or viruses that can harm your device or data. Use it at your own risk.
  • -
  • Tesla Mod may not be compatible with all devices or versions of Car Parking Multiplayer. It may cause crashes, glitches, or errors in the game. Make sure you backup your game data before using it.
  • -
  • Tesla Mod may violate the terms and conditions of Car Parking Multiplayer. It may result in a ban or suspension from the game or online services. Use it at your own discretion.
  • -
-

Conclusion

-

Summary of the main points

-

In conclusion, Car Parking Multiplayer APK Tesla Mod is a modified version of Car Parking Multiplayer that allows you to drive a Tesla car in the game and use its advanced features. It is a fun and exciting way to enjoy the game and experience the benefits of a Tesla car. However, it is also a risky and unofficial app that may cause problems for your device or game account. Therefore, you should use it with caution and discretion. If you want to download and install Tesla Mod, you can follow the steps we have provided in this article. You can also use the tips and tricks we have shared to make the most of Tesla Mod in Car Parking Multiplayer.

-

Call to action

-

Are you ready to try Tesla Mod in Car Parking Multiplayer? If yes, then go ahead and download it from the link below. But remember, use it at your own risk and responsibility. And don't forget to share your feedback and experience with us in the comments section. We would love to hear from you. Happy parking!

-

FAQs

-

Here are some of the frequently asked questions about Tesla Mod in Car Parking Multiplayer:

-
    -
  1. Q: Is Tesla Mod free to use?
    -A: Yes, Tesla Mod is free to download and use. However, you may need to watch ads or complete surveys to access some features or download links.
  2. -
  3. Q: Is Tesla Mod safe to use?
    -A: Tesla Mod is not a verified or authorized app by Tesla or Car Parking Multiplayer developers. It may contain malware or viruses that can harm your device or data. Use it at your own risk.
  4. -
  5. Q: Can I use Tesla Mod with other mods or hacks?
    -A: We do not recommend using Tesla Mod with other mods or hacks, as it may cause conflicts or errors in the game. Use it only with the original version of Car Parking Multiplayer.
  6. -
  7. Q: Can I use Tesla Mod offline?
    -A: Yes, you can use Tesla Mod offline in single-player mode. However, you may need an internet connection to download and install it, and to access some features or updates.
  8. -
  9. Q: Can I use Tesla Mod on iOS devices?
    -A: No, Tesla Mod is only available for Android devices. There is no iOS version of Tesla Mod as of now.
  10. -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Juega con la Pou APK y descubre todos los secretos de Pou.md b/spaces/congsaPfin/Manga-OCR/logs/Juega con la Pou APK y descubre todos los secretos de Pou.md deleted file mode 100644 index 8f2ea6698d89976ca7321706a938ac0f0aeaa1dd..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Juega con la Pou APK y descubre todos los secretos de Pou.md +++ /dev/null @@ -1,144 +0,0 @@ - -

La Pou APK: A Fun and Cute Virtual Pet Game for Android

-

Do you love virtual pet games? Do you want to have a cute and funny alien as your pet? If you answered yes to these questions, then you should try La Pou APK, a popular and entertaining game for Android devices. In this game, you can adopt, care for, play with, and customize your own Pou, a brown blob-like creature that lives in your phone. You can also interact with other players and their Pous, making this game more social and fun. In this article, we will tell you everything you need to know about La Pou APK, including what it is, how to download and install it, how to play it, how to customize it, and how to interact with other players.

-

What is La Pou APK?

-

La Pou APK is an Android application that allows you to play the game of La Pou on your mobile device. La Pou is a virtual pet game that was created by Zakeh, a Lebanese game developer, in 2012. The game has been downloaded over 500 million times and has received positive reviews from users and critics alike.

-

la pou apk


Download >>>>> https://urlca.com/2uOffP



-

The concept of La Pou

-

The concept of La Pou is simple but addictive. You have to take care of your Pou, a cute alien that looks like a brown blob with eyes and a mouth. You have to feed it, clean it, play with it, and watch it grow as you level up. You also have to make sure that your Pou is happy, healthy, and well-rested by monitoring its four indicators: hunger, health, fun, and energy. If you neglect your Pou, it will become sad, sick, or tired.

-

The features of La Pou

-

La Pou has many features that make it more than just a virtual pet game. Some of these features are:

-
    -
  • You can choose the gender and name of your Pou.
  • -
  • You can access different rooms in your house, such as the kitchen, the bedroom, the bathroom, the living room, the garden, and the game room.
  • -
  • You can play various mini-games with your Pou or by yourself, such as Tic Tac Toe, Connect Four, Match Tap, Memory Game, Sky Jump, Hill Drive, Food Drop, Color Match, and more.
  • -
  • You can customize your Pou's appearance by changing its color, shape, eyes, mouth, accessories, outfits, hats, eyeglasses, and wallpapers.
  • -
  • You can unlock achievements and special items by completing tasks or reaching milestones.
  • -
  • You can visit and play with your friends' Pous or make new friends by chatting with other players.
  • -
  • You can talk to your Pou and listen to it repeat what you say in a funny voice.
  • -
-

How to download and install La Pou APK on your Android device?

-

If you want to play La Pou on your Android device, you need to download and install the APK file of the game. An APK file is an application package file that contains all the files needed to run an Android app. Here are the requirements and steps for downloading and installing La Pou APK on your Android device.

-

The requirements for La Pou APK

-

Before you download and install La Pou APK, you need to make sure that your Android device meets the following requirements:

-
    -
  • Your device must have Android 4.1 or higher.
  • -
  • Your device must have at least 50 MB of free storage space.
  • -
  • Your device must have a stable internet connection.
  • -
  • Your device must allow the installation of unknown apps from your browser or file manager app. You can enable this option by following the steps in the previous section.
  • -
-

The steps to download and install La Pou APK

-

Once you have checked the requirements, you can follow these steps to download and install La Pou APK on your Android device:

-
    -
  1. Open your browser and go to a website that offers the La Pou APK file. You can search for "La Pou APK" on Google or use one of these links: . Make sure you only download the APK file from a reputable source.
  2. -
  3. Tap on the download link or button and wait for the APK file to be downloaded on your device. You should see a notification on the top bar of your device when the download is complete.
  4. -
  5. Open your file manager app and locate the APK file in the Downloads folder. Tap on the APK file to open it.
  6. -
  7. You may see a warning message that says "This type of file can harm your device". Tap on OK to proceed.
  8. -
  9. You may also see a prompt that asks you to confirm the installation of unknown apps. Tap on Settings and then toggle on the switch next to Allow from this source. Tap on the back button to return to the installation screen.
  10. -
  11. Tap on Install and wait for the installation process to finish. You should see a message that says "App installed" when it is done.
  12. -
  13. Tap on Open to launch the La Pou app or tap on Done to exit the installation screen. You can also find the La Pou app icon on your home screen or app drawer.
  14. -
-

How to play La Pou APK on your Android device?

-

Now that you have installed La Pou APK on your Android device, you can start playing with your virtual pet. Here are some tips on how to play La Pou APK on your Android device:

-

la pou apk download
-la pou apk mod
-la pou apk hack
-la pou apk unlimited coins
-la pou apk latest version
-la pou apk android
-la pou apk free
-la pou apk full
-la pou apk offline
-la pou apk update
-la pou apk 2023
-la pou apk old version
-la pou apk for pc
-la pou apk uptodown
-la pou apk revdl
-la pou apk pure
-la pou apk mirror
-la pou apk no ads
-la pou apk premium
-la pou apk pro
-la pou apk cracked
-la pou apk cheat
-la pou apk game
-la pou apk app
-la pou apk online
-la pou apk 1.4.81
-la pou apk 1.4.79
-la pou apk 1.4.77
-la pou apk 1.4.75
-la pou apk 1.4.74
-la pou apk 1.4.73
-la pou apk 1.4.72
-la pou apk 1.4.71
-la pou apk 1.4.69
-la pou apk 1.4.67
-la pou apk 1.4.66
-la pou apk 1.4.65
-la pou apk 1.4.64
-la pou apk 1.4.63
-la pou apk 1.4.62
-la pou apk 1.4.61
-la pou apk 1.4.60
-la pou apk 1.4.59
-la pou apk 1.4.58
-la pou apk 1.4.57

-

The main screen of La Pou

-

The main screen of La Pou shows your Pou in its house. You can see its name, gender, level, coins, and indicators at the top of the screen. You can also see four icons at the bottom of the screen: Menu, Lab, Shop, and Friends. These icons allow you to access different features of the game.

-

The different rooms of La Pou

-

You can swipe left or right on the main screen to switch between different rooms in your house. Each room has a different function and a different mini-game that you can play with your Pou. Here are the rooms and their functions:

- - - - - - - - -
RoomFunctionMini-game
KitchenYou can feed your Pou with various foods and drinks. You can also drag and drop food items into its mouth or tap on them to make them fall from above.Hungry Pou: You have to catch as many falling food items as possible with your mouth before time runs out.
BedroomYou can put your Pou to sleep by turning off the lights. You can also wake it up by turning them back on or tapping on it. Sleeping restores your Pou's energy level.Dream Pou: You have to tap on matching pairs of dream bubbles before they disappear.
BathroomYou can clean your Pou by using soap, water, and a towel. You can also flush the toilet after it uses it. Cleaning improves your Pou's health level.Pou Popper: You have to pop as many bubbles as possible by tapping on them before they reach the top of the screen.
Living RoomYou can talk to your Pou by using the microphone icon. Your Pou will repeat what you say in a funny voice. You can also change its voice pitch by using the slider. Talking increases your Pou's fun level.Pou Sounds: You have to repeat the sounds that your Pou makes by tapping on the corresponding buttons.
GardenYou can take your Pou outside and enjoy the fresh air and the scenery. You can also plant flowers and fruits in the garden and water them. Gardening also boosts your Pou's fun level.Flower Pop: You have to tap on the flowers that match the color of the center flower before they disappear.
Game RoomYou can play more mini-games with your Pou or by yourself. You can choose from a variety of games, such as Tic Tac Toe, Connect Four, Match Tap, Memory Game, Sky Jump, Hill Drive, Food Drop, Color Match, and more. Playing mini-games earns you coins and increases your Pou's fun level.Varies depending on the game you choose.
-

The mini-games of La Pou

-

The mini-games of La Pou are one of the most enjoyable aspects of the game. They are fun, challenging, and rewarding. You can play them with your Pou or by yourself. You can also choose the difficulty level of each game, from easy to hard. Some of the mini-games are:

-
    -
  • Tic Tac Toe: A classic game where you have to make a line of three Xs or Os before your opponent does.
  • -
  • Connect Four: A strategy game where you have to drop colored discs into a grid and make a line of four discs of your color before your opponent does.
  • -
  • Match Tap: A reflex game where you have to tap on the tiles that match the color or shape of the center tile before they disappear.
  • -
  • Memory Game: A memory game where you have to flip over cards and match pairs of images.
  • -
  • Sky Jump: A jumping game where you have to guide your Pou through the sky and avoid obstacles.
  • -
  • Hill Drive: A driving game where you have to control your car on a hilly terrain and collect coins and fuel.
  • -
  • Food Drop: A catching game where you have to catch as many falling food items as possible with your mouth before time runs out.
  • -
  • Color Match: A matching game where you have to tap on the bubbles that match the color of the center bubble before they reach the top of the screen.
  • -
-

How to customize La Pou APK on your Android device?

-

One of the best features of La Pou APK is that you can customize your Pou's appearance and personality. You can make your Pou look unique and express yourself through it. Here are some ways to customize La Pou APK on your Android device:

-

The lab of La Pou

-

The lab of La Pou is where you can change your Pou's color and shape. You can use different potions to transform your Pou into different colors, such as blue, green, pink, purple, red, yellow, and more. You can also use special potions to change your Pou's shape, such as square, star, heart, triangle, and more. You can buy potions from the shop or get them for free by watching ads or completing offers.

-

The shop of La Pou

-

The shop of La Pou is where you can buy various items to customize your Pou's appearance and house. You can use coins that you earn from playing mini-games or watching ads to buy items from different categories, such as eyes, mouth, accessories, outfits, hats, eyeglasses, and wallpapers. You can also buy food and drinks for your Pou from the shop.

-

The achievements and special items of La Pou

-

The achievements and special items of La Pou are rewards that you can unlock by completing tasks or reaching milestones in the game. For example, you can unlock achievements by reaching a certain level, feeding your Pou a certain number of times, playing a certain number of mini-games, visiting a certain number of friends, and more. You can also unlock special items by collecting puzzle pieces from playing mini-games or visiting friends. These items include sunglasses, headphones, necklaces, bracelets, rings, and more.

-

How to interact with other players in La Pou APK on your Android device?

-

La Pou APK is not only a virtual pet game but also a social game. You can interact with other players and their Pous in various ways. Here are some ways to interact with other players in La Pou APK on your Android device:

-

The friends of La Pou

-

The friends of La Pou are other players that you can add to your friend list. You can visit their Pous and play with them in their rooms. You can also send them gifts or messages. You can add friends by using their usernames or scanning their QR codes. You can also find random friends by using the Find button.

-

The chat of La Pou

-

The The chat of La Pou is where you can communicate with other players and their Pous in real time. You can join different chat rooms based on your language or interest. You can also create your own chat room and invite your friends. You can send text messages, emojis, stickers, or voice messages. You can also play mini-games with other players in the chat room.

-

Conclusion

-

La Pou APK is a fun and cute virtual pet game for Android devices. You can adopt, care for, play with, and customize your own Pou, a brown blob-like alien that lives in your phone. You can also interact with other players and their Pous, making this game more social and fun. La Pou APK is easy to download and install on your Android device. You just need to follow the requirements and steps that we have explained in this article. La Pou APK is a game that will keep you entertained and engaged for hours. If you love virtual pet games, you should definitely try La Pou APK.

-

FAQs

-

Here are some frequently asked questions about La Pou APK:

-
    -
  • Q: Is La Pou APK free to play?
  • -
  • A: Yes, La Pou APK is free to play. However, it contains ads and in-app purchases that you can use to buy coins or items.
  • -
  • Q: How can I backup or restore my Pou?
  • -
  • A: You can backup or restore your Pou by using the cloud icon in the menu. You need to create an account or log in with your email or Facebook to use this feature.
  • -
  • Q: How can I change the language of La Pou?
  • -
  • A: You can change the language of La Pou by using the settings icon in the menu. You can choose from over 30 languages, such as English, Spanish, French, German, Italian, Portuguese, Arabic, Chinese, Japanese, Korean, and more.
  • -
  • Q: How can I contact the developer of La Pou?
  • -
  • A: You can contact the developer of La Pou by using the contact icon in the menu. You can send an email to pou@pou.me or visit their website at www.pou.me.
  • -
  • Q: How can I rate or review La Pou?
  • -
  • A: You can rate or review La Pou by using the rate icon in the menu. You can also rate or review La Pou on Google Play Store or other app stores where you downloaded it.
  • -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/My Talking Tom MOD APK The Ultimate Guide to Unlimited Fun.md b/spaces/congsaPfin/Manga-OCR/logs/My Talking Tom MOD APK The Ultimate Guide to Unlimited Fun.md deleted file mode 100644 index 07ea1c5ee848d8adeea77d942f1717cfa24de558..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/My Talking Tom MOD APK The Ultimate Guide to Unlimited Fun.md +++ /dev/null @@ -1,85 +0,0 @@ -
-

My Talking Tom Unlimited Coins and Diamonds Mod APK: A Fun and Interactive Game for All Ages

-

Do you love cats? Do you want to have a virtual pet that you can take care of, play with, and customize? If yes, then you should try My Talking Tom, a legendary virtual cat breeding game on the mobile platform. In this game, you can adopt your own kitten, name it Tom, and watch it grow from a cute baby to a full-grown cat. You can also feed it, dress it, pet it, tickle it, talk to it, and play with it in various ways. But what if you want to have more fun and freedom in the game? What if you want to have unlimited coins and diamonds to buy all the items and outfits you want for your Tom? Well, there is a way to do that. You can download and install My Talking Tom Unlimited Coins and Diamonds Mod APK, a modified version of the game that gives you access to unlimited resources and features. In this article, we will tell you more about My Talking Tom, My Talking Tom Unlimited Coins and Diamonds Mod APK, and how to download and install it on your device.

-

my talking tom unlimited coins and diamonds mod apk


Download Filehttps://urlca.com/2uO6yQ



-

What is My Talking Tom?

-

My Talking Tom is a virtual cat breeding game developed by Outfit7 Limited, a company that specializes in creating games featuring talking animals. The game was released in 2013 and has since become one of the most popular games on the mobile platform. It has over 500 million downloads on Google Play Store and has received positive reviews from users and critics alike. The game is suitable for all ages, as it is easy to play, fun to watch, and interactive to engage with.

-

Features of My Talking Tom

-

My Talking Tom has many features that make it an enjoyable game for cat lovers and casual gamers. Here are some of them:

-

Customize your Tom

-

You can customize your Tom in various ways, such as changing its fur color, eye color, shape, size, and accessories. You can also dress it up in different outfits, such as hats, glasses, clothes, shoes, and more. You can even give it tattoos or piercings if you want. There are hundreds of items and outfits to choose from, so you can create your own unique Tom.

-

Play mini-games with your Tom

-

You can play mini-games with your Tom to earn coins and have fun. There are over 10 mini-games to choose from, such as Flappy Tom, Bubble Shooter, Planet Hop, Happy Connect, Brick Blast, Memory Match, Cake Tower, Space Trails, Connect The Dots, Jigsaw Puzzle, and more. Each mini-game has different levels of difficulty and rewards. You can also compete with other players online and see who can get the highest score.

-

Interact with your Tom and other players

-

You can interact with your Tom in various ways, such as feeding it, bathing it, brushing its teeth, putting it to bed, petting it, tickling it, poking it, slapping it, throwing it in the air, or making it fart. You can also talk to it using your voice or text messages. Your Tom will repeat what you say in a funny voice or respond with its own words. You can also visit other players' Toms online and see how they look like. You can chat with them, send them gifts, or play with their Toms. You can also join clubs and chat with other members who share your interests.

-

What is My Talking Tom Unlimited Coins and Diamonds Mod APK?

-

My Talking Tom Unlimited Coins and Diamonds Mod APK is a modified version of the original game that gives you access to unlimited coins and diamonds, as well as other features that are not available in the official version. Coins and diamonds are the main currencies in the game, which you can use to buy items and outfits for your Tom, or to unlock new mini-games and features. However, earning coins and diamonds in the game can be time-consuming and tedious, as you have to play mini-games, watch ads, or complete tasks. Moreover, some items and outfits are very expensive and require a lot of coins and diamonds to purchase. That's why many players look for ways to get unlimited coins and diamonds in the game, such as using cheats, hacks, or mod apk files.

-

Benefits of My Talking Tom Unlimited Coins and Diamonds Mod APK

-

My Talking Tom Unlimited Coins and Diamonds Mod APK has many benefits that make it a better choice than the original game. Here are some of them:

-

Get unlimited coins and diamonds

-

With My Talking Tom Unlimited Coins and Diamonds Mod APK, you can get unlimited coins and diamonds in the game without spending any real money or wasting any time. You can use these coins and diamonds to buy anything you want for your Tom, such as food, clothes, accessories, furniture, toys, etc. You can also use them to unlock new mini-games and features that are otherwise locked or limited in the original game. You can enjoy the game without any restrictions or limitations.

-

My Talking Tom MOD APK 7.6.0.3422 (Unlimited Money) - APKdone[^1^]
-Download My Talking Tom Mod Apk v7.6.0.3422 (Unlimited Coins/Diamonds)
-My Talking Tom Hack Mod Apk - How to Get Free Coins and Diamonds
-My Talking Tom Unlimited Money and Gems Mod Apk Latest Version
-My Talking Tom Mod Apk 7.6.0.3422 (Unlimited Coins/Diamonds) for Android
-My Talking Tom Cheats - How to Hack Coins and Diamonds Easily
-My Talking Tom Mod Apk Download (Unlimited Money/Gems) 2023
-My Talking Tom Free Coins and Diamonds Generator - No Survey No Human Verification
-My Talking Tom Mod Apk 7.6.0.3422 - Unlimited Coins and Diamonds Hack
-My Talking Tom Mod Apk (Unlimited Money/Gems) - Outfit7 Limited
-How to Install My Talking Tom Mod Apk (Unlimited Coins/Diamonds) on Android
-My Talking Tom Mod Apk 7.6.0.3422 - Download for Free (Unlimited Money/Gems)
-My Talking Tom Hack Tool - Get Unlimited Coins and Diamonds Online
-My Talking Tom Mod Apk (Unlimited Money/Gems) - Best Virtual Pet Game
-My Talking Tom Unlimited Coins and Diamonds Mod Apk for PC
-My Talking Tom Mod Apk 7.6.0.3422 (Unlimited Money/Gems) - APKPure
-My Talking Tom Hack Apk - Unlimited Coins and Diamonds Cheat
-My Talking Tom Mod Apk (Unlimited Money/Gems) - Latest Update 2023
-My Talking Tom Free Coins and Diamonds - How to Get Them Fast
-My Talking Tom Mod Apk 7.6.0.3422 - Unlimited Coins and Diamonds Download
-My Talking Tom Hack Online - Generate Free Coins and Diamonds Now
-My Talking Tom Mod Apk (Unlimited Money/Gems) - Fun and Interactive Game
-My Talking Tom Unlimited Coins and Diamonds Mod Apk for iOS
-My Talking Tom Mod Apk 7.6.0.3422 - Download Link (Unlimited Money/Gems)
-My Talking Tom Cheat Codes - How to Use Them to Get More Coins and Diamonds
-My Talking Tom Mod Apk (Unlimited Money/Gems) - Features and Gameplay
-My Talking Tom Unlimited Coins and Diamonds Mod Apk for Windows Phone
-My Talking Tom Mod Apk 7.6.0.3422 - How to Install (Unlimited Money/Gems)
-My Talking Tom Hack No Root - How to Get Coins and Diamonds Without Rooting Your Device
-My Talking Tom Mod Apk (Unlimited Money/Gems) - Review and Rating

-

Unlock all items and outfits

-

With My Talking Tom Unlimited Coins and Diamonds Mod APK, you can unlock all the items and outfits in the game without having to play for hours or complete tasks. You can have access to hundreds of items and outfits that are otherwise unavailable or hard to get in the original game. You can customize your Tom in any way you want, from its fur color to its clothes style. You can also change its appearance anytime you want without losing any coins or diamonds.

-

Enjoy ad-free gaming experience

-

With My Talking Tom Unlimited Coins and Diamonds Mod APK, you can enjoy an ad-free gaming experience without having to watch annoying ads or pay for premium subscriptions. Ads can be very distracting and irritating when you are playing the game, as they can interrupt your gameplay, slow down your device, or consume your data. Moreover, some ads can be misleading or harmful to your device security. With My Talking Tom Unlimited Coins and Diamonds Mod APK, you can play the game without any ads or pop-ups.

-

How to download and install My Talking Tom Unlimited Coins and Diamonds Mod APK?

-

If you want to download and install My Talking Tom Unlimited Coins and Diamonds Mod APK on your device, you need to follow some simple steps. However, before you do that, you need to make sure that your device meets the minimum requirements for the game. These are:

-
    -
  • Android version 4.4 or higher
  • -
  • At least 1 GB of RAM
  • -
  • At least 100 MB of free storage space
  • -
  • A stable internet connection
  • -
-

If your device meets these requirements, you can proceed with the following steps:

-

Steps to download and install My Talking Tom Unlimited Coins and Diamonds Mod APK

-

Download the mod apk file from a trusted source

-

The first step is to download the mod apk file from a trusted source. There are many websites that offer mod apk files for various games, but not all of them are safe or reliable. Some of them may contain viruses, malware, spyware, or other harmful elements that can damage your device or steal your personal information. Therefore, you need to be careful when choosing a source for downloading the mod apk file. You can use Google search or ask for recommendations from other players who have used the mod apk file before. You can also check the reviews, ratings, comments, or feedbacks of other users who have downloaded the mod apk file from the same source.

-

Enable unknown sources on your device settings

-

The second step is to enable unknown sources on your device settings. This is necessary because by default, your device does not allow installing apps from sources other than Google Play Store. However, since you are installing a mod apk file that is not available on Google Play Store, you need to enable unknown sources on your device settings. To do this, you need to follow these steps:

-
    -
  1. Go to your device settings
  2. -
  3. Tap with, and interact with. However, if you want to have more fun and freedom in the game, you can download and install My Talking Tom Unlimited Coins and Diamonds Mod APK, a modified version of the game that gives you access to unlimited coins and diamonds, as well as other features that are not available in the official version. You can use these coins and diamonds to buy anything you want for your Tom, unlock all items and outfits, and enjoy an ad-free gaming experience. You can also download and install My Talking Tom Unlimited Coins and Diamonds Mod APK easily by following the steps we have provided in this article. We hope you found this article helpful and informative. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

    -

    FAQs

    -

    Here are some frequently asked questions about My Talking Tom Unlimited Coins and Diamonds Mod APK:

    -

    Is My Talking Tom Unlimited Coins and Diamonds Mod APK safe to use?

    -

    Yes, My Talking Tom Unlimited Coins and Diamonds Mod APK is safe to use, as long as you download it from a trusted source and enable unknown sources on your device settings. However, you should always be careful when downloading and installing any mod apk file, as some of them may contain viruses, malware, spyware, or other harmful elements that can damage your device or steal your personal information. You should also scan the mod apk file with an antivirus or anti-malware program before installing it.

    -

    Will I get banned for using My Talking Tom Unlimited Coins and Diamonds Mod APK?

    -

    No, you will not get banned for using My Talking Tom Unlimited Coins and Diamonds Mod APK, as the mod apk file does not interfere with the game's servers or online features. You can play the game offline or online without any problems. However, you should not use the mod apk file to cheat or abuse the game's rules or other players, as that may result in a ban or suspension from the game.

    -

    Can I update My Talking Tom Unlimited Coins and Diamonds Mod APK?

    -

    No, you cannot update My Talking Tom Unlimited Coins and Diamonds Mod APK, as the mod apk file is not compatible with the official version of the game. If you try to update the game from Google Play Store or other sources, you will lose all the modded features and resources. Therefore, you should avoid updating the game if you want to keep using the mod apk file. You should also disable automatic updates on your device settings to prevent accidental updates.

    -

    Can I use My Talking Tom Unlimited Coins and Diamonds Mod APK on iOS devices?

    -

    No, you cannot use My Talking Tom Unlimited Coins and Diamonds Mod APK on iOS devices, as the mod apk file is only compatible with Android devices. iOS devices have a different operating system and file format than Android devices, so they cannot run mod apk files. If you want to use a modified version of the game on iOS devices, you will need to use a different method, such as jailbreaking your device or using a third-party app store.

    -

    Can I use My Talking Tom Unlimited Coins and Diamonds Mod APK with other mods or hacks?

    -

    No, you cannot use My Talking Tom Unlimited Coins and Diamonds Mod APK with other mods or hacks, as they may cause conflicts or errors in the game. The mod apk file already contains all the features and resources you need to enjoy the game without any limitations or restrictions. You should not use any other mods or hacks that may alter the game's data or functionality.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Unmatched Air Traffic Control Mod APK 2022.06 Get Unlimited Money and Coins.md b/spaces/congsaPfin/Manga-OCR/logs/Unmatched Air Traffic Control Mod APK 2022.06 Get Unlimited Money and Coins.md deleted file mode 100644 index f59be03f2bfe18cbe7dadfdda5e2a5dddbb60942..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Unmatched Air Traffic Control Mod APK 2022.06 Get Unlimited Money and Coins.md +++ /dev/null @@ -1,84 +0,0 @@ -
    -

    Download Unmatched Air Traffic Control Mod APK 2022.06 Unlimited Money

    -

    If you are a fan of simulation games, especially air traffic control games, then you will love Unmatched Air Traffic Control. This game lets you experience the thrill and challenge of managing the busy airspace of various airports around the world. You have to guide the planes to land and take off safely, avoid collisions, and keep the passengers happy. But what if you want to enjoy the game without any limitations or restrictions? Well, you can do that by downloading Unmatched Air Traffic Control Mod APK, which gives you unlimited money and access to all the planes in the game. In this article, we will tell you more about this amazing mod apk, its features, and how to download and install it on your Android device.

    -

    download unmatched air traffic control mod apk 2022.06 unlimited money


    DOWNLOAD ✓✓✓ https://urlca.com/2uO5bG



    -

    Introduction

    -

    What is Unmatched Air Traffic Control?

    -

    Unmatched Air Traffic Control is a realistic and addictive simulation game developed by Vector3D Studios. The game has over 10 million downloads on Google Play Store and a rating of 4.4 out of 5 stars. The game simulates the operation of a busy airport, where you have to control the air traffic and ensure the safety and efficiency of the flights. You have to deal with different weather conditions, emergencies, delays, and other factors that affect the air traffic. You can choose from different airports and scenarios, each with its own challenges and difficulties. You can also unlock and use different planes, from small propellers to large jets, each with its own characteristics and performance.

    -

    Why download Unmatched Air Traffic Control Mod APK?

    -

    While Unmatched Air Traffic Control is a fun and engaging game, it also has some drawbacks that may affect your gaming experience. For example, you need to earn money in the game to unlock new planes and airports, which can take a lot of time and effort. You also have to watch ads to get some extra money or rewards, which can be annoying and distracting. Moreover, some of the planes and airports are only available through in-app purchases, which means you have to spend real money to get them.

    -

    That's why downloading Unmatched Air Traffic Control Mod APK is a great idea if you want to enjoy the game without any limitations or restrictions. This mod apk gives you unlimited money in the game, which means you can unlock and use any plane or airport you want without spending a dime. You also don't have to watch any ads or make any in-app purchases, as everything is already unlocked for you. This way, you can focus on the gameplay and have more fun controlling the air traffic.

    -

    Features of Unmatched Air Traffic Control Mod APK

    -

    Unlimited money

    -

    The most obvious and attractive feature of Unmatched Air Traffic Control Mod APK is that it gives you unlimited money in the game. Money is the main currency in the game, which you need to unlock new planes and airports. Normally, you have to earn money by completing missions, watching ads, or making in-app purchases. But with this mod apk, you don't have to worry about that anymore. You will get unlimited money as soon as you start the game, which means you can buy anything you want without any hassle.

    -

    All planes unlocked

    -

    Another feature of Unmatched Air Traffic Control Mod APK is that it unlocks all the planes in the game for you. There are over 50 different planes in the game, each with its own design, speed, capacity, and fuel consumption. Some of the planes are free to use, while others require money or in-app purchases to unlock. But with this mod apk, you can access all the planes without any restrictions. You can choose from small propellers, helicopters, jets, cargo planes, military planes, and more. You can also switch between different planes as you wish, and enjoy their different features and capabilities.

    -

    Realistic graphics and sound effects

    -

    Unmatched Air Traffic Control Mod APK also enhances the graphics and sound effects of the game, making it more realistic and immersive. The game has high-quality 3D graphics that depict the airports, planes, and surroundings in great detail. You can see the shadows, lights, reflections, and textures of the objects in the game. You can also zoom in and out, rotate, and change the camera angle to get a better view of the action. The game also has realistic sound effects that match the movements and actions of the planes and the air traffic. You can hear the engines, horns, brakes, and communications of the pilots and controllers. You can also adjust the volume and sound settings according to your preference.

    -

    Multiple airports and scenarios

    -

    Another feature of Unmatched Air Traffic Control Mod APK is that it gives you access to multiple airports and scenarios in the game. There are over 20 different airports in the game, each with its own layout, size, traffic, and difficulty level. Some of the airports are based on real-world locations, such as New York, London, Paris, Tokyo, Dubai, and more. You can also choose from different scenarios, such as day or night, clear or cloudy, calm or stormy, and more. Each scenario has its own challenges and effects on the air traffic. You can also customize the settings of the game, such as the number of planes, the speed of time, and the difficulty level.

    -

    Easy and intuitive controls

    -

    The last feature of Unmatched Air Traffic Control Mod APK is that it makes the controls of the game easy and intuitive. The game has a simple and user-friendly interface that shows you all the information and options you need to control the air traffic. You can use touch gestures to select, drag, tap, or swipe on the screen to perform various actions. You can also use buttons and menus to access different functions and features of the game. The game also has a tutorial mode that guides you through the basics of the game and teaches you how to control the planes.

    -

    How to download unmatched air traffic control mod apk 2022.06 with unlimited money
    -Unmatched air traffic control mod apk 2022.06 unlimited money free download for android
    -Unmatched air traffic control hack mod apk 2022.06 unlimited money and coins
    -Download latest version of unmatched air traffic control mod apk 2022.06 with unlimited money and all planes unlocked
    -Unmatched air traffic control mod apk 2022.06 unlimited money no root required
    -Unmatched air traffic control simulation game mod apk 2022.06 unlimited money and gems
    -Unmatched air traffic control mod apk 2022.06 unlimited money offline mode
    -Unmatched air traffic control cheats mod apk 2022.06 unlimited money and gold
    -Unmatched air traffic control premium mod apk 2022.06 unlimited money and diamonds
    -Unmatched air traffic control pro mod apk 2022.06 unlimited money and everything
    -Download unmatched air traffic control mod apk 2022.06 with unlimited money and realistic graphics
    -Unmatched air traffic control mod apk 2022.06 unlimited money online multiplayer
    -Unmatched air traffic control cracked mod apk 2022.06 unlimited money and keys
    -Unmatched air traffic control full mod apk 2022.06 unlimited money and vip
    -Unmatched air traffic control mega mod apk 2022.06 unlimited money and resources
    -Download unmatched air traffic control mod apk 2022.06 with unlimited money and no ads
    -Unmatched air traffic control modded apk 2022.06 unlimited money and features
    -Unmatched air traffic control hack apk download 2022.06 unlimited money and rewards
    -Unmatched air traffic control best mod apk 2022.06 unlimited money and levels
    -Unmatched air traffic control ultimate mod apk 2022.06 unlimited money and planes
    -Download unmatched air traffic control mod apk 2022.06 with unlimited money and high quality sound
    -Unmatched air traffic control super mod apk 2022.06 unlimited money and missions
    -Unmatched air traffic control patched mod apk 2022.06 unlimited money and skins
    -Unmatched air traffic control latest mod apk download 2022.06 unlimited money and items
    -Unmatched air traffic control new mod apk 2022.06 unlimited money and modes
    -Download unmatched air traffic control mod apk 2022.06 with unlimited money and easy controls
    -Unmatched air traffic control awesome mod apk 2022.06 unlimited money and fun
    -Unmatched air traffic control cool mod apk 2022.06 unlimited money and challenges
    -Unmatched air traffic control amazing mod apk 2022.06 unlimited money and achievements
    -Unmatched air traffic controller updated mod apk download 2022.06 unlimited money and stars
    -Download unmatched air traffic controller mod apk 2022.06 with unlimited money and smooth gameplay
    -Unmatched air traffic controller fantastic mod apk 2022.06 unlimited money and ratings
    -Unmatched air traffic controller wonderful mod apk 2022.06 unlimited money and reviews
    -Unmatched air traffic controller great mod apk download 2022.06 unlimited money and support
    -Unmatched air traffic controller perfect mod apk 2022.06 unlimited money and quality

    -

    How to download and install Unmatched Air Traffic Control Mod APK?

    -

    Step 1: Enable unknown sources

    -

    The first step to download and install Unmatched Air Traffic Control Mod APK is to enable unknown sources on your Android device. This will allow you to install apps from sources other than Google Play Store. To do this, go to your device settings > security > unknown sources > enable.

    -

    Step 2: Download the mod apk file

    -

    The next step is to download the mod apk file from a reliable source. You can use this link to download Unmatched Air Traffic Control Mod APK 2022.06 Unlimited Money for free. The file size is about 300 MB, so make sure you have enough space on your device.

    -

    Step 3: Install the mod apk file

    -

    The third step is to install the mod apk file on your device. To do this, locate the downloaded file in your file manager or downloads folder. Tap on it to start the installation process. Follow the instructions on the screen to complete the installation.

    -

    Step 4: Launch the game and enjoy

    -

    The final step is to launch the game and enjoy it. You will see a new icon on your home screen or app drawer for Unmatched Air Traffic Control Mod APK. Tap on it to open the game and enjoy it. You will see that you have unlimited money in the game and all the planes and airports are unlocked for you. You can also customize the settings and choose the scenario you want to play. Have fun controlling the air traffic and becoming the best air traffic controller in the world.

    -

    Conclusion

    -

    Unmatched Air Traffic Control is a realistic and addictive simulation game that lets you experience the thrill and challenge of managing the busy airspace of various airports around the world. You have to guide the planes to land and take off safely, avoid collisions, and keep the passengers happy. You can also unlock and use different planes, from small propellers to large jets, each with its own characteristics and performance. However, if you want to enjoy the game without any limitations or restrictions, you should download Unmatched Air Traffic Control Mod APK, which gives you unlimited money and access to all the planes in the game. You also don't have to watch any ads or make any in-app purchases, as everything is already unlocked for you. This way, you can focus on the gameplay and have more fun controlling the air traffic.

    -

    We hope this article has helped you learn more about Unmatched Air Traffic Control Mod APK, its features, and how to download and install it on your Android device. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and happy gaming!

    -

    FAQs

    -

    Here are some frequently asked questions about Unmatched Air Traffic Control Mod APK:

    -
      -
    • Is Unmatched Air Traffic Control Mod APK safe to download and install?
    • -

      Yes, Unmatched Air Traffic Control Mod APK is safe to download and install, as long as you get it from a reliable source. The mod apk file does not contain any viruses or malware that can harm your device or data. However, you should always scan the file before installing it, just to be on the safe side.

      -
    • Do I need to root my device to use Unmatched Air Traffic Control Mod APK?
    • -

      No, you don't need to root your device to use Unmatched Air Traffic Control Mod APK. The mod apk works fine on both rooted and non-rooted devices. However, if you have a rooted device, you may get some extra benefits and features from the mod apk.

      -
    • Will I get banned from the game if I use Unmatched Air Traffic Control Mod APK?
    • -

      No, you will not get banned from the game if you use Unmatched Air Traffic Control Mod APK. The mod apk does not interfere with the online servers or features of the game. It only modifies the offline aspects of the game, such as money and planes. Therefore, you can use it without any risk of getting banned.

      -
    • Can I update Unmatched Air Traffic Control Mod APK?
    • -

      Yes, you can update Unmatched Air Traffic Control Mod APK whenever there is a new version available. However, you should always backup your data before updating, as some updates may cause compatibility issues or data loss. You should also check if the new version has any new features or changes that may affect your gameplay.

      -
    • Can I play Unmatched Air Traffic Control Mod APK with my friends?
    • -

      Yes, you can play Unmatched Air Traffic Control Mod APK with your friends, as long as they also have the same mod apk installed on their devices. You can connect with them through Wi-Fi or Bluetooth and enjoy controlling the air traffic together.

      -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/AlphaROM LINK Cracker X2.rar.md b/spaces/contluForse/HuggingGPT/assets/AlphaROM LINK Cracker X2.rar.md deleted file mode 100644 index 171af2e775293b989ab3f6b2cb1579ee2a31cea9..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/AlphaROM LINK Cracker X2.rar.md +++ /dev/null @@ -1,12 +0,0 @@ -
    -

    the thing what i did was install the game and use the crack,download this crack.alpharom cracker x2.rar of this torrent. coub.com/stories/2170440-dido-life-for-rent-download-rar-greyamar..com/pondbladalop/post/alpharom-cracker-x2-rar

    -

    AlphaROM Cracker x2.rar


    Downloadhttps://ssurll.com/2uzycp



    -

    alpharom cracker x2.rar ->>->>->> alfa romeo
    alpharomdie
    alfa romeo 4c
    alpharom
    alfa romeo suv
    related. civil 3d 2012 crack 64 bit torrent torrent autocad 2010 crack 32 bit free download alpharom cracker x2.rar. microsoft access 97 portable.

    -

    download katfile: + & web + alpharom cracker x2 + exe. topics: yah-yah-doh rar, [aa2][animation][more cumming positions][fix by al, x v i d e o s japan, alpharom cracker x2, x v i d e o s, [aa2][animation][more.

    -

    download: + & web + alpharom cracker x2 + exe. topics: yah-yah-doh rar, [aa2][animation][more cumming positions][fix by al, x v i d e o s japan, alpharom cracker x2, x v i d e o s, [aa2][animation][more.

    -

    company: zion. alpharom cracker x2.rar. sample download freakshare. extract the contents of the 'alpharom cracker x2' rar file (this should come together with your iso file) into your game installation.

    -

    download: alpharom cracker x2 + exe.
    choose [open file] and select the file 'alpharom cracker x2' that you downloaded above.
    click on [extract all].
    click on [show all files] to view the extracted files.
    close the [show all files] box.
    click on [exit].
    double click on the icon named 'alpharom cracker x2.exe' to run the game.

    -

    download: alpharom cracker x2 + exe.
    choose [open file] and select the file 'alpharom cracker x2' that you downloaded above.
    click on [extract all].
    click on [show all files] to view the extracted files.
    close the [show all files] box.
    click on [exit].
    double click on the icon named 'alpharom cracker x2.exe' to run the game.

    -

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Enjoy the music from the Grisaia series with the Grisaia Phantom Trigger Soundtrack mod download.md b/spaces/contluForse/HuggingGPT/assets/Enjoy the music from the Grisaia series with the Grisaia Phantom Trigger Soundtrack mod download.md deleted file mode 100644 index 16851d2262a89dcb113be3dd4afa0961e7e3feeb..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Enjoy the music from the Grisaia series with the Grisaia Phantom Trigger Soundtrack mod download.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Grisaia Phantom Trigger Soundtrack mod download


    Download Zip ✒ ✒ ✒ https://ssurll.com/2uzvZA



    -
    - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/cooelf/Multimodal-CoT/timm/models/layers/cond_conv2d.py b/spaces/cooelf/Multimodal-CoT/timm/models/layers/cond_conv2d.py deleted file mode 100644 index 8b4bbca84d6f12e0fb875b4edb435b976fc649d6..0000000000000000000000000000000000000000 --- a/spaces/cooelf/Multimodal-CoT/timm/models/layers/cond_conv2d.py +++ /dev/null @@ -1,122 +0,0 @@ -""" PyTorch Conditionally Parameterized Convolution (CondConv) - -Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference -(https://arxiv.org/abs/1904.04971) - -Hacked together by / Copyright 2020 Ross Wightman -""" - -import math -from functools import partial -import numpy as np -import torch -from torch import nn as nn -from torch.nn import functional as F - -from .helpers import to_2tuple -from .conv2d_same import conv2d_same -from .padding import get_padding_value - - -def get_condconv_initializer(initializer, num_experts, expert_shape): - def condconv_initializer(weight): - """CondConv initializer function.""" - num_params = np.prod(expert_shape) - if (len(weight.shape) != 2 or weight.shape[0] != num_experts or - weight.shape[1] != num_params): - raise (ValueError( - 'CondConv variables must have shape [num_experts, num_params]')) - for i in range(num_experts): - initializer(weight[i].view(expert_shape)) - return condconv_initializer - - -class CondConv2d(nn.Module): - """ Conditionally Parameterized Convolution - Inspired by: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/condconv/condconv_layers.py - - Grouped convolution hackery for parallel execution of the per-sample kernel filters inspired by this discussion: - https://github.com/pytorch/pytorch/issues/17983 - """ - __constants__ = ['in_channels', 'out_channels', 'dynamic_padding'] - - def __init__(self, in_channels, out_channels, kernel_size=3, - stride=1, padding='', dilation=1, groups=1, bias=False, num_experts=4): - super(CondConv2d, self).__init__() - - self.in_channels = in_channels - self.out_channels = out_channels - self.kernel_size = to_2tuple(kernel_size) - self.stride = to_2tuple(stride) - padding_val, is_padding_dynamic = get_padding_value( - padding, kernel_size, stride=stride, dilation=dilation) - self.dynamic_padding = is_padding_dynamic # if in forward to work with torchscript - self.padding = to_2tuple(padding_val) - self.dilation = to_2tuple(dilation) - self.groups = groups - self.num_experts = num_experts - - self.weight_shape = (self.out_channels, self.in_channels // self.groups) + self.kernel_size - weight_num_param = 1 - for wd in self.weight_shape: - weight_num_param *= wd - self.weight = torch.nn.Parameter(torch.Tensor(self.num_experts, weight_num_param)) - - if bias: - self.bias_shape = (self.out_channels,) - self.bias = torch.nn.Parameter(torch.Tensor(self.num_experts, self.out_channels)) - else: - self.register_parameter('bias', None) - - self.reset_parameters() - - def reset_parameters(self): - init_weight = get_condconv_initializer( - partial(nn.init.kaiming_uniform_, a=math.sqrt(5)), self.num_experts, self.weight_shape) - init_weight(self.weight) - if self.bias is not None: - fan_in = np.prod(self.weight_shape[1:]) - bound = 1 / math.sqrt(fan_in) - init_bias = get_condconv_initializer( - partial(nn.init.uniform_, a=-bound, b=bound), self.num_experts, self.bias_shape) - init_bias(self.bias) - - def forward(self, x, routing_weights): - B, C, H, W = x.shape - weight = torch.matmul(routing_weights, self.weight) - new_weight_shape = (B * self.out_channels, self.in_channels // self.groups) + self.kernel_size - weight = weight.view(new_weight_shape) - bias = None - if self.bias is not None: - bias = torch.matmul(routing_weights, self.bias) - bias = bias.view(B * self.out_channels) - # move batch elements with channels so each batch element can be efficiently convolved with separate kernel - x = x.view(1, B * C, H, W) - if self.dynamic_padding: - out = conv2d_same( - x, weight, bias, stride=self.stride, padding=self.padding, - dilation=self.dilation, groups=self.groups * B) - else: - out = F.conv2d( - x, weight, bias, stride=self.stride, padding=self.padding, - dilation=self.dilation, groups=self.groups * B) - out = out.permute([1, 0, 2, 3]).view(B, self.out_channels, out.shape[-2], out.shape[-1]) - - # Literal port (from TF definition) - # x = torch.split(x, 1, 0) - # weight = torch.split(weight, 1, 0) - # if self.bias is not None: - # bias = torch.matmul(routing_weights, self.bias) - # bias = torch.split(bias, 1, 0) - # else: - # bias = [None] * B - # out = [] - # for xi, wi, bi in zip(x, weight, bias): - # wi = wi.view(*self.weight_shape) - # if bi is not None: - # bi = bi.view(*self.bias_shape) - # out.append(self.conv_fn( - # xi, wi, bi, stride=self.stride, padding=self.padding, - # dilation=self.dilation, groups=self.groups)) - # out = torch.cat(out, 0) - return out diff --git a/spaces/cooelf/Multimodal-CoT/timm/utils/summary.py b/spaces/cooelf/Multimodal-CoT/timm/utils/summary.py deleted file mode 100644 index 9f5af9a08598556c3fed136f258f88bd578c1e1c..0000000000000000000000000000000000000000 --- a/spaces/cooelf/Multimodal-CoT/timm/utils/summary.py +++ /dev/null @@ -1,39 +0,0 @@ -""" Summary utilities - -Hacked together by / Copyright 2020 Ross Wightman -""" -import csv -import os -from collections import OrderedDict -try: - import wandb -except ImportError: - pass - -def get_outdir(path, *paths, inc=False): - outdir = os.path.join(path, *paths) - if not os.path.exists(outdir): - os.makedirs(outdir) - elif inc: - count = 1 - outdir_inc = outdir + '-' + str(count) - while os.path.exists(outdir_inc): - count = count + 1 - outdir_inc = outdir + '-' + str(count) - assert count < 100 - outdir = outdir_inc - os.makedirs(outdir) - return outdir - - -def update_summary(epoch, train_metrics, eval_metrics, filename, write_header=False, log_wandb=False): - rowd = OrderedDict(epoch=epoch) - rowd.update([('train_' + k, v) for k, v in train_metrics.items()]) - rowd.update([('eval_' + k, v) for k, v in eval_metrics.items()]) - if log_wandb: - wandb.log(rowd) - with open(filename, mode='a') as cf: - dw = csv.DictWriter(cf, fieldnames=rowd.keys()) - if write_header: # first iteration (epoch == 1 can't be used) - dw.writeheader() - dw.writerow(rowd) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/deeplab/config.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/deeplab/config.py deleted file mode 100644 index 5f5e45a9124e61c12d90cfc5032b268496891a4a..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/deeplab/config.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. - - -def add_deeplab_config(cfg): - """ - Add config for DeepLab. - """ - # We retry random cropping until no single category in semantic segmentation GT occupies more - # than `SINGLE_CATEGORY_MAX_AREA` part of the crop. - cfg.INPUT.CROP.SINGLE_CATEGORY_MAX_AREA = 1.0 - # Used for `poly` learning rate schedule. - cfg.SOLVER.POLY_LR_POWER = 0.9 - cfg.SOLVER.POLY_LR_CONSTANT_ENDING = 0.0 - # Loss type, choose from `cross_entropy`, `hard_pixel_mining`. - cfg.MODEL.SEM_SEG_HEAD.LOSS_TYPE = "hard_pixel_mining" - # DeepLab settings - cfg.MODEL.SEM_SEG_HEAD.PROJECT_FEATURES = ["res2"] - cfg.MODEL.SEM_SEG_HEAD.PROJECT_CHANNELS = [48] - cfg.MODEL.SEM_SEG_HEAD.ASPP_CHANNELS = 256 - cfg.MODEL.SEM_SEG_HEAD.ASPP_DILATIONS = [6, 12, 18] - cfg.MODEL.SEM_SEG_HEAD.ASPP_DROPOUT = 0.1 - cfg.MODEL.SEM_SEG_HEAD.USE_DEPTHWISE_SEPARABLE_CONV = False - # Backbone new configs - cfg.MODEL.RESNETS.RES4_DILATION = 1 - cfg.MODEL.RESNETS.RES5_MULTI_GRID = [1, 2, 4] - # ResNet stem type from: `basic`, `deeplab` - cfg.MODEL.RESNETS.STEM_TYPE = "deeplab" diff --git a/spaces/cozyanduofen/bingo/src/lib/isomorphic/index.ts b/spaces/cozyanduofen/bingo/src/lib/isomorphic/index.ts deleted file mode 100644 index 738dc92f74079ab762d584fb7422a8c8c3b61547..0000000000000000000000000000000000000000 --- a/spaces/cozyanduofen/bingo/src/lib/isomorphic/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -'use client' - -import Default from './browser' - -let exportsModel: any = {} - -if (process.browser) { - Object.assign(exportsModel, require('./browser').default) -} else { - Object.assign(exportsModel, require('./node').default) -} - -export default exportsModel! as typeof Default - -export const fetch: typeof Default.fetch = exportsModel!.fetch -export const WebSocket: typeof Default.WebSocket = exportsModel!.WebSocket -export const debug: typeof Default.debug = exportsModel!.debug diff --git a/spaces/cppowboy/viscpm-chat/app.py b/spaces/cppowboy/viscpm-chat/app.py deleted file mode 100644 index 0f920a8eaebc81651404dcc738a1229b9c0ae00c..0000000000000000000000000000000000000000 --- a/spaces/cppowboy/viscpm-chat/app.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# encoding: utf-8 -import gradio as gr -from PIL import Image -import requests -import base64 -from io import BytesIO -import traceback -import os - - -def upload_img(image,_chatbot,_app_session): - image = Image.fromarray(image) - _app_session['sts']=None - _app_session['ctx']='' - _app_session['img']=image - _chatbot.append(('图片解析成功,可以和我对话了', '')) - return _chatbot,_app_session - - -def respond( _question, _chat_bot,_app_cfg): - try: - img = _app_cfg['img'] - buffered = BytesIO() - img.save(buffered, format="JPEG") - img_str = base64.b64encode(buffered.getvalue()).decode('utf-8') - url = os.environ['SERVICE_URL'] - resp = requests.post(url, headers={ - "X-Model-Best-Model": "viscpm-chat-balance", - "X-Model-Best-Trace-ID": "test-trace", - }, json={ - "image": img_str, - "question": _question, - }) - resp = resp.json() - # _answer = resp['data']['response'] - print('get response', resp) - _answer = resp['response'] - print(f'question: {_question}, answer: {_answer}') - except Exception as e: - print(traceback.format_exc()) - if resp is not None: - print(resp.content) - _answer = "请求失败" - _chat_bot.append((_question, _answer)) - _context = _app_cfg['ctx'] + '\n' + _question + '\n' + _answer + '\n' - sts = None - _app_cfg['ctx'] = _context - _app_cfg['sts'] = sts - return '', _chat_bot, _app_cfg - - -with gr.Blocks() as demo: - app_session = gr.State({'sts':None,'ctx':None,'img':None}) - bt_pic = gr.Image(label="先上传一张图片") - chat_bot = gr.Chatbot(label="聊天对话") - txt_message = gr.Textbox(label="输入文字") - - txt_message.submit(respond, [ txt_message, chat_bot,app_session], [txt_message,chat_bot,app_session]) - bt_pic.upload(lambda: None, None, chat_bot, queue=False).then(upload_img, inputs=[bt_pic,chat_bot,app_session], outputs=[chat_bot,app_session]) - - -demo.queue(concurrency_count=1, max_size=20).launch(share=False, debug=True) \ No newline at end of file diff --git a/spaces/csuhan/opendet2/opendet2/modeling/meta_arch/retinanet.py b/spaces/csuhan/opendet2/opendet2/modeling/meta_arch/retinanet.py deleted file mode 100644 index dc013bfc4fd6927be186f2a4957d535c3c96466d..0000000000000000000000000000000000000000 --- a/spaces/csuhan/opendet2/opendet2/modeling/meta_arch/retinanet.py +++ /dev/null @@ -1,483 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import logging -from typing import Dict, List, Tuple - -import numpy as np -import torch -import torch.distributions as dists -from detectron2.config import configurable -from detectron2.layers import ShapeSpec, cat, cross_entropy -from detectron2.modeling import META_ARCH_REGISTRY -from detectron2.modeling.box_regression import _dense_box_regression_loss -from detectron2.modeling.meta_arch.retinanet import RetinaNet, RetinaNetHead -from detectron2.modeling.postprocessing import detector_postprocess -from detectron2.structures import Boxes, Instances, pairwise_iou -from detectron2.utils.events import get_event_storage -from fvcore.nn import sigmoid_focal_loss_jit -from torch import Tensor, nn -from torch.nn import functional as F - -from ..layers import ConvMLP -from ..losses import ICLoss - -logger = logging.getLogger(__name__) - - -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 UPLoss(nn.Module): - """Unknown Probability Loss for RetinaNet - """ - - def __init__(self, - num_classes: int, - sampling_metric: str = "min_score", - topk: int = 3, - alpha: float = 1.0): - super().__init__() - self.num_classes = num_classes - assert sampling_metric in ["min_score", "max_entropy", "random"] - self.sampling_metric = sampling_metric - # if topk==-1, sample len(fg)*2 examples - self.topk = topk - self.alpha = alpha - - def _soft_cross_entropy(self, input: Tensor, target: Tensor): - logprobs = F.log_softmax(input, dim=1) - return -(target * logprobs).sum() / input.shape[0] - - def _sampling(self, scores: Tensor, labels: Tensor): - fg_inds = labels != self.num_classes - fg_scores, fg_labels = scores[fg_inds], labels[fg_inds] - - # remove unknown classes - _fg_scores = torch.cat( - [fg_scores[:, :self.num_classes-1], fg_scores[:, -1:]], dim=1) - - num_fg = fg_scores.size(0) - topk = num_fg if (self.topk == -1) or (num_fg < - self.topk) else self.topk - # use maximum entropy as a metric for uncertainty - # we select topk proposals with maximum entropy - if self.sampling_metric == "max_entropy": - pos_metric = dists.Categorical( - _fg_scores.softmax(dim=1)).entropy() - # use minimum score as a metric for uncertainty - # we select topk proposals with minimum max-score - elif self.sampling_metric == "min_score": - pos_metric = -_fg_scores.max(dim=1)[0] - # we randomly select topk proposals - elif self.sampling_metric == "random": - pos_metric = torch.rand(_fg_scores.size(0),).to(scores.device) - - _, pos_inds = pos_metric.topk(topk) - fg_scores, fg_labels = fg_scores[pos_inds], fg_labels[pos_inds] - - return fg_scores, fg_labels - - def forward(self, scores: Tensor, labels: Tensor): - scores, labels = self._sampling(scores, labels) - - num_sample, num_classes = scores.shape - mask = torch.arange(num_classes).repeat( - num_sample, 1).to(scores.device) - inds = mask != labels[:, None].repeat(1, num_classes) - mask = mask[inds].reshape(num_sample, num_classes-1) - - gt_scores = torch.gather( - F.softmax(scores, dim=1), 1, labels[:, None]).squeeze(1) - mask_scores = torch.gather(scores, 1, mask) - - gt_scores[gt_scores < 0] = 0.0 - targets = torch.zeros_like(mask_scores) - targets[:, self.num_classes-2] = gt_scores * \ - (1-gt_scores).pow(self.alpha) - - return self._soft_cross_entropy(mask_scores, targets.detach()) - - -@META_ARCH_REGISTRY.register() -class OpenSetRetinaNet(RetinaNet): - """ - Implement RetinaNet in :paper:`RetinaNet`. - """ - - @configurable - def __init__( - self, - num_known_classes, - max_iters, - up_loss_start_iter, - up_loss_sampling_metric, - up_loss_topk, - up_loss_alpha, - up_loss_weight, - ins_con_out_dim, - ins_con_queue_size, - ins_con_in_queue_size, - ins_con_batch_iou_thr, - ins_con_queue_iou_thr, - ins_con_queue_tau, - ins_con_loss_weight, - *args, - **kargs, - ): - super().__init__(*args, **kargs) - self.num_known_classes = num_known_classes - self.max_iters = max_iters - - self.up_loss = UPLoss( - self.num_classes, - sampling_metric=up_loss_sampling_metric, - topk=up_loss_topk, - alpha=up_loss_alpha - ) - self.up_loss_start_iter = up_loss_start_iter - self.up_loss_weight = up_loss_weight - - self.ins_con_loss = ICLoss(tau=ins_con_queue_tau) - self.ins_con_out_dim = ins_con_out_dim - self.ins_con_queue_size = ins_con_queue_size - self.ins_con_in_queue_size = ins_con_in_queue_size - self.ins_con_batch_iou_thr = ins_con_batch_iou_thr - self.ins_con_queue_iou_thr = ins_con_queue_iou_thr - self.ins_con_loss_weight = ins_con_loss_weight - - self.register_buffer('queue', torch.zeros( - self.num_known_classes, ins_con_queue_size, ins_con_out_dim)) - self.register_buffer('queue_label', torch.empty( - self.num_known_classes, ins_con_queue_size).fill_(-1).long()) - self.register_buffer('queue_ptr', torch.zeros( - self.num_known_classes, dtype=torch.long)) - - @classmethod - def from_config(cls, cfg): - ret = super().from_config(cfg) - backbone_shape = ret["backbone"].output_shape() - feature_shapes = [backbone_shape[f] for f in cfg.MODEL.RETINANET.IN_FEATURES] - head = OpenSetRetinaNetHead(cfg, feature_shapes) - ret.update({ - "head": head, - "num_known_classes": cfg.MODEL.ROI_HEADS.NUM_KNOWN_CLASSES, - "max_iters": cfg.SOLVER.MAX_ITER, - - "up_loss_start_iter": cfg.UPLOSS.START_ITER, - "up_loss_sampling_metric": cfg.UPLOSS.SAMPLING_METRIC, - "up_loss_topk": cfg.UPLOSS.TOPK, - "up_loss_alpha": cfg.UPLOSS.ALPHA, - "up_loss_weight": cfg.UPLOSS.WEIGHT, - - "ins_con_out_dim": cfg.ICLOSS.OUT_DIM, - "ins_con_queue_size": cfg.ICLOSS.QUEUE_SIZE, - "ins_con_in_queue_size": cfg.ICLOSS.IN_QUEUE_SIZE, - "ins_con_batch_iou_thr": cfg.ICLOSS.BATCH_IOU_THRESH, - "ins_con_queue_iou_thr": cfg.ICLOSS.QUEUE_IOU_THRESH, - "ins_con_queue_tau": cfg.ICLOSS.TEMPERATURE, - "ins_con_loss_weight": cfg.ICLOSS.WEIGHT, - }) - return ret - - def get_up_loss(self, scores, gt_classes): - # start up loss after warmup iters - storage = get_event_storage() - if storage.iter > self.up_loss_start_iter: - loss_cls_up = self.up_loss(scores, gt_classes) - else: - loss_cls_up = scores.new_tensor(0.0) - - return self.up_loss_weight * loss_cls_up - - def get_ins_con_loss(self, feat, gt_classes, ious): - # select foreground and iou > thr instance in a mini-batch - pos_inds = (ious > self.ins_con_batch_iou_thr) & ( - gt_classes != self.num_classes) - - if not pos_inds.sum(): - return feat.new_tensor(0.0) - - feat, gt_classes = feat[pos_inds], gt_classes[pos_inds] - - queue = self.queue.reshape(-1, self.ins_con_out_dim) - queue_label = self.queue_label.reshape(-1) - queue_inds = queue_label != -1 # filter empty queue - queue, queue_label = queue[queue_inds], queue_label[queue_inds] - - loss_ins_con = self.ins_con_loss(feat, gt_classes, queue, queue_label) - # loss decay - storage = get_event_storage() - decay_weight = 1.0 - storage.iter / self.max_iters - return self.ins_con_loss_weight * decay_weight * loss_ins_con - - @ torch.no_grad() - def _dequeue_and_enqueue(self, feat, gt_classes, ious, iou_thr=0.7): - # 1. gather variable - # feat = self.concat_all_gather(feat) - # gt_classes = self.concat_all_gather(gt_classes) - # ious = self.concat_all_gather(ious) - # 2. filter by iou and obj, remove bg - keep = (ious > iou_thr) & (gt_classes != self.num_classes) - feat, gt_classes = feat[keep], gt_classes[keep] - - for i in range(self.num_known_classes): - ptr = int(self.queue_ptr[i]) - cls_ind = gt_classes == i - cls_feat, cls_gt_classes = feat[cls_ind], gt_classes[cls_ind] - # 3. sort by similarity, low sim ranks first - cls_queue = self.queue[i, self.queue_label[i] != -1] - _, sim_inds = F.cosine_similarity( - cls_feat[:, None], cls_queue[None, :], dim=-1).mean(dim=1).sort() - top_sim_inds = sim_inds[:self.ins_con_in_queue_size] - cls_feat, cls_gt_classes = cls_feat[top_sim_inds], cls_gt_classes[top_sim_inds] - # 4. in queue - batch_size = cls_feat.size( - 0) if ptr + cls_feat.size(0) <= self.ins_con_queue_size else self.ins_con_queue_size - ptr - self.queue[i, ptr:ptr+batch_size] = cls_feat[:batch_size] - self.queue_label[i, ptr:ptr + - batch_size] = cls_gt_classes[:batch_size] - - ptr = ptr + batch_size if ptr + batch_size < self.ins_con_queue_size else 0 - self.queue_ptr[i] = ptr - - @ torch.no_grad() - def concat_all_gather(self, tensor): - tensors_gather = [torch.ones_like(tensor) for _ in range( - torch.distributed.get_world_size())] - torch.distributed.all_gather(tensors_gather, tensor, async_op=False) - output = torch.cat(tensors_gather, dim=0) - return output - - 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] - - anchors = self.anchor_generator(features) - pred_logits, pred_anchor_deltas, pred_mlp_feats = self.head(features) - # Transpose the Hi*Wi*A dimension to the middle: - pred_logits = [permute_to_N_HWA_K( - x, self.num_classes) for x in pred_logits] - pred_anchor_deltas = [permute_to_N_HWA_K( - x, 4) for x in pred_anchor_deltas] - pred_mlp_feats = [permute_to_N_HWA_K( - x, self.ins_con_out_dim) for x in pred_mlp_feats] - - 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] - - gt_labels, gt_boxes, gt_ious = self.label_anchors( - anchors, gt_instances) - losses = self.losses(anchors, pred_logits, pred_mlp_feats, - gt_labels, pred_anchor_deltas, gt_boxes, gt_ious) - - if self.vis_period > 0: - storage = get_event_storage() - if storage.iter % self.vis_period == 0: - results = self.inference( - anchors, pred_logits, pred_anchor_deltas, images.image_sizes - ) - self.visualize_training(batched_inputs, results) - - return losses - else: - results = self.inference( - anchors, pred_logits, pred_anchor_deltas, images.image_sizes) - 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 losses(self, anchors, pred_logits, pred_mlp_feats, gt_labels, pred_anchor_deltas, gt_boxes, gt_ious): - """ - Args: - anchors (list[Boxes]): a list of #feature level Boxes - gt_labels, gt_boxes: see output of :meth:`RetinaNet.label_anchors`. - Their shapes are (N, R) and (N, R, 4), respectively, where R is - the total number of anchors across levels, i.e. sum(Hi x Wi x Ai) - pred_logits, pred_anchor_deltas: both are list[Tensor]. Each element in the - list corresponds to one level and has shape (N, Hi * Wi * Ai, K or 4). - Where K is the number of classes used in `pred_logits`. - - Returns: - dict[str, Tensor]: - mapping from a named loss to a scalar tensor - storing the loss. Used during training only. The dict keys are: - "loss_cls" and "loss_box_reg" - """ - num_images = len(gt_labels) - gt_labels = torch.stack(gt_labels) # (N, R) - - valid_mask = gt_labels >= 0 - pos_mask = (gt_labels >= 0) & (gt_labels != self.num_classes) - num_pos_anchors = pos_mask.sum().item() - get_event_storage().put_scalar("num_pos_anchors", num_pos_anchors / num_images) - self.loss_normalizer = self.loss_normalizer_momentum * self.loss_normalizer + ( - 1 - self.loss_normalizer_momentum - ) * max(num_pos_anchors, 1) - - # classification and regression loss - gt_labels_target = F.one_hot(gt_labels[valid_mask], num_classes=self.num_classes + 1)[ - :, :-1 - ] # no loss for the last (background) class - - loss_cls_ce = sigmoid_focal_loss_jit( - cat(pred_logits, dim=1)[valid_mask], - gt_labels_target.to(pred_logits[0].dtype), - alpha=self.focal_loss_alpha, - gamma=self.focal_loss_gamma, - reduction="sum", - ) - - loss_cls_up = self.get_up_loss(cat(pred_logits, dim=1)[ - valid_mask], gt_labels[valid_mask]) - - gt_ious = torch.stack(gt_ious) - # we first store feats in the queue, then cmopute the loss - pred_mlp_feats = cat(pred_mlp_feats, dim=1)[valid_mask] # [N, *, 128] - # [N*, 128] - pred_mlp_feats = pred_mlp_feats.reshape(-1, pred_mlp_feats.shape[-1]) - self._dequeue_and_enqueue( - pred_mlp_feats, gt_labels[valid_mask], gt_ious[valid_mask], iou_thr=self.ins_con_queue_iou_thr) - loss_ins_con = self.get_ins_con_loss( - pred_mlp_feats, gt_labels[valid_mask], gt_ious[valid_mask]) - - loss_box_reg = _dense_box_regression_loss( - anchors, - self.box2box_transform, - pred_anchor_deltas, - gt_boxes, - pos_mask, - box_reg_loss_type=self.box_reg_loss_type, - smooth_l1_beta=self.smooth_l1_beta, - ) - - return { - "loss_cls_ce": loss_cls_ce / self.loss_normalizer, - "loss_box_reg": loss_box_reg / self.loss_normalizer, - "loss_ins_con": loss_ins_con, - "loss_cls_up": loss_cls_up, - } - - @torch.no_grad() - def label_anchors(self, anchors, gt_instances): - - anchors = Boxes.cat(anchors) # Rx4 - - gt_labels = [] - matched_gt_boxes = [] - matched_gt_ious = [] - for gt_per_image in gt_instances: - match_quality_matrix = pairwise_iou(gt_per_image.gt_boxes, anchors) - matched_idxs, anchor_labels = self.anchor_matcher( - match_quality_matrix) - # del match_quality_matrix - - if len(gt_per_image) > 0: - matched_gt_boxes_i = gt_per_image.gt_boxes.tensor[matched_idxs] - matched_gt_ious_i = match_quality_matrix.max(dim=1)[ - 0][matched_idxs] - - gt_labels_i = gt_per_image.gt_classes[matched_idxs] - # Anchors with label 0 are treated as background. - gt_labels_i[anchor_labels == 0] = self.num_classes - # Anchors with label -1 are ignored. - gt_labels_i[anchor_labels == -1] = -1 - else: - matched_gt_boxes_i = torch.zeros_like(anchors.tensor) - matched_gt_ious_i = torch.zeros_like(matched_idxs) - gt_labels_i = torch.zeros_like(matched_idxs) + self.num_classes - - gt_labels.append(gt_labels_i) - matched_gt_boxes.append(matched_gt_boxes_i) - matched_gt_ious.append(matched_gt_ious_i) - - del match_quality_matrix - - return gt_labels, matched_gt_boxes, matched_gt_ious - - -class OpenSetRetinaNetHead(RetinaNetHead): - """ - The head used in RetinaNet for object classification and box regression. - It has two subnets for the two tasks, with a common structure but separate parameters. - """ - - @configurable - def __init__( - self, - *args, - ins_con_out_dim, - **kargs - ): - super().__init__(*args, **kargs) - self.mlp = ConvMLP(kargs["conv_dims"][-1], ins_con_out_dim * kargs["num_anchors"]) - - @classmethod - def from_config(cls, cfg, input_shape: List[ShapeSpec]): - ret = super().from_config(cfg, input_shape) - ret["ins_con_out_dim"] = cfg.ICLOSS.OUT_DIM - return ret - - def forward(self, features: List[Tensor]): - """ - Arguments: - features (list[Tensor]): FPN feature map tensors in high to low resolution. - Each tensor in the list correspond to different feature levels. - - Returns: - logits (list[Tensor]): #lvl tensors, each has shape (N, AxK, Hi, Wi). - The tensor predicts the classification probability - at each spatial position for each of the A anchors and K object - classes. - bbox_reg (list[Tensor]): #lvl tensors, each has shape (N, Ax4, Hi, Wi). - The tensor predicts 4-vector (dx,dy,dw,dh) box - regression values for every anchor. These values are the - relative offset between the anchor and the ground truth box. - """ - logits = [] - mlp_feats = [] - bbox_reg = [] - for feature in features: - cls_feat = self.cls_subnet(feature) - mlp_feats.append(self.mlp(cls_feat)) - logits.append(self.cls_score(cls_feat)) - - bbox_reg.append(self.bbox_pred(self.bbox_subnet(feature))) - return logits, bbox_reg, mlp_feats diff --git a/spaces/cxeep/whisper-webui/app-local.py b/spaces/cxeep/whisper-webui/app-local.py deleted file mode 100644 index b1e539ac7062c648dd3ad9048900d0f96b1ef033..0000000000000000000000000000000000000000 --- a/spaces/cxeep/whisper-webui/app-local.py +++ /dev/null @@ -1,3 +0,0 @@ -# Run the app with no audio file restrictions -from app import createUi -createUi(-1) \ No newline at end of file diff --git a/spaces/cymic/Talking_Head_Anime_3/README.md b/spaces/cymic/Talking_Head_Anime_3/README.md deleted file mode 100644 index 7c37030f2366fe37b81ec3d19247794d599c30ca..0000000000000000000000000000000000000000 --- a/spaces/cymic/Talking_Head_Anime_3/README.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Talking Head Anime 3 -emoji: 👩‍🎤 -colorFrom: blue -colorTo: indigo -sdk: gradio -sdk_version: 3.18.0 -app_file: app.py -pinned: false ---- - -# Demo Code for "Talking Head(?) Anime from A Single Image 3: Now the Body Too" - -This repository contains demo programs for the [Talking Head(?) Anime from a Single Image 3: Now the Body Too](https://pkhungurn.github.io/talking-head-anime-3/index.html) project. As the name implies, the project allows you to animate anime characters, and you only need a single image of that character to do so. There are two demo programs: - -* The ``manual_poser`` lets you manipulate a character's facial expression, head rotation, body rotation, and chest expansion due to breathing through a graphical user interface. -* ``ifacialmocap_puppeteer`` lets you transfer your facial motion to an anime character. - -## Try the Manual Poser on Google Colab - -If you do not have the required hardware (discussed below) or do not want to download the code and set up an environment to run it, click [![this link](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pkhungurn/talking-head-anime-3-demo/blob/master/colab.ipynb) to try running the manual poser on [Google Colab](https://research.google.com/colaboratory/faq.html). - -## Hardware Requirements - -Both programs require a recent and powerful Nvidia GPU to run. I could personally ran them at good speed with the Nvidia Titan RTX. However, I think recent high-end gaming GPUs such as the RTX 2080, the RTX 3080, or better would do just as well. - -The `ifacialmocap_puppeteer` requires an iOS device that is capable of computing [blend shape parameters](https://developer.apple.com/documentation/arkit/arfaceanchor/2928251-blendshapes) from a video feed. This means that the device must be able to run iOS 11.0 or higher and must have a TrueDepth front-facing camera. (See [this page](https://developer.apple.com/documentation/arkit/content_anchors/tracking_and_visualizing_faces) for more info.) In other words, if you have the iPhone X or something better, you should be all set. Personally, I have used an iPhone 12 mini. - -## Software Requirements - -### GPU Related Software - -Please update your GPU's device driver and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit) that is compatible with your GPU and is newer than the version you will be installing in the next subsection. - -### Python Environment - -Both ``manual_poser`` and ``ifacialmocap_puppeteer`` are available as desktop applications. To run them, you need to set up an environment for running programs written in the [Python](http://www.python.org) language. The environment needs to have the following software packages: - -* Python >= 3.8 -* PyTorch >= 1.11.0 with CUDA support -* SciPY >= 1.7.3 -* wxPython >= 4.1.1 -* Matplotlib >= 3.5.1 - -One way to do so is to install [Anaconda](https://www.anaconda.com/) and run the following commands in your shell: - -``` -> conda create -n talking-head-anime-3-demo python=3.8 -> conda activate talking-head-anime-3-demo -> conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch -> conda install scipy -> pip install wxpython -> conda install matplotlib -``` - -#### Caveat 1: Do not use Python 3.10 on Windows - -As of June 2006, you cannot use [wxPython](https://www.wxpython.org/) with Python 3.10 on Windows. As a result, do not use Python 3.10 until [this bug](https://github.com/wxWidgets/Phoenix/issues/2024) is fixed. This means you should not set ``python=3.10`` in the first ``conda`` command in the listing above. - -#### Caveat 2: Adjust versions of Python and CUDA Toolkit as needed - -The environment created by the commands above gives you Python version 3.8 and an installation of [PyTorch](http://pytorch.org) that was compiled with CUDA Toolkit version 11.3. This particular setup might not work in the future because you may find that this particular PyTorch package does not work with your new computer. The solution is to: - -1. Change the Python version in the first command to a recent one that works for your OS. (That is, do not use 3.10 if you are using Windows.) -2. Change the version of CUDA toolkit in the third command to one that the PyTorch's website says is available. In particular, scroll to the "Install PyTorch" section and use the chooser there to pick the right command for your computer. Use that command to install PyTorch instead of the third command above. - -![The command to install PyTorch](docs/pytorch-install-command.png "The command to install PyTorch") - -### Jupyter Environment - -The ``manual_poser`` is also available as a [Jupyter Nootbook](http://jupyter.org). To run it on your local machines, you also need to install: - -* Jupyter Notebook >= 7.3.4 -* IPywidgets >= 7.7.0 - -In some case, you will also need to enable the ``widgetsnbextension`` as well. So, run - -``` -> jupyter nbextension enable --py widgetsnbextension -``` - -After installing the above two packages. Using Anaconda, I managed to do the above with the following commands: - -``` -> conda install -c conda-forge notebook -> conda install -c conda-forge ipywidgets -> jupyter nbextension enable --py widgetsnbextension -``` - -### Automatic Environment Construction with Anaconda - -You can also use Anaconda to download and install all Python packages in one command. Open your shell, change the directory to where you clone the repository, and run: - -``` -> conda env create -f environment.yml -``` - -This will create an environment called ``talking-head-anime-3-demo`` containing all the required Python packages. - -### iFacialMocap - -If you want to use ``ifacialmocap_puppeteer``, you will also need to an iOS software called [iFacialMocap](https://www.ifacialmocap.com/) (a 980 yen purchase in the App Store). You do not need to download the paired application this time. Your iOS and your computer must use the same network. For example, you may connect them to the same wireless router. - -## Download the Models - -Before running the programs, you need to download the model files from this [Dropbox link](https://www.dropbox.com/s/y7b8jl4n2euv8xe/talking-head-anime-3-models.zip?dl=0) and unzip it to the ``data/models`` folder under the repository's root directory. In the end, the data folder should look like: - -``` -+ data - + images - - crypko_00.png - - crypko_01.png - : - - crypko_07.png - - lambda_00.png - - lambda_01.png - + models - + separable_float - - editor.pt - - eyebrow_decomposer.pt - - eyebrow_morphing_combiner.pt - - face_morpher.pt - - two_algo_face_body_rotator.pt - + separable_half - - editor.pt - : - - two_algo_face_body_rotator.pt - + standard_float - - editor.pt - : - - two_algo_face_body_rotator.pt - + standard_half - - editor.pt - : - - two_algo_face_body_rotator.pt -``` - -The model files are distributed with the -[Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/legalcode), which -means that you can use them for commercial purposes. However, if you distribute them, you must, among other things, say -that I am the creator. - -## Running the `manual_poser` Desktop Application - -Open a shell. Change your working directory to the repository's root directory. Then, run: - -``` -> python tha3/app/manual_poser.py -``` - -Note that before running the command above, you might have to activate the Python environment that contains the required -packages. If you created an environment using Anaconda as was discussed above, you need to run - -``` -> conda activate talking-head-anime-3-demo -``` - -if you have not already activated the environment. - -### Choosing System Variant to Use - -As noted in the [project's write-up](http://pkhungurn.github.io/talking-head-anime-3/index.html), I created 4 variants of the neural network system. They are called ``standard_float``, ``separable_float``, ``standard_half``, and ``separable_half``. All of them have the same functionalities, but they differ in their sizes, RAM usage, speed, and accuracy. You can specify which variant that the ``manual_poser`` program uses through the ``--model`` command line option. - -``` -> python tha3/app/manual_poser --model -``` - -where ```` must be one of the 4 names above. If no variant is specified, the ``standard_float`` variant (which is the largest, slowest, and most accurate) will be used. - -## Running the `manual_poser` Jupyter Notebook - -Open a shell. Activate the environment. Change your working directory to the repository's root directory. Then, run: - -``` -> jupyter notebook -``` - -A browser window should open. In it, open `manual_poser.ipynb`. Once you have done so, you should see that it has two cells. Run the two cells in order. Then, scroll down to the end of the document, and you'll see the GUI there. - -You can choose the system variant to use by changing the ``MODEL_NAME`` variable in the first cell. If you do, you will need to rerun both cells in order for the variant to be loaded and the GUI to be properly updated to use it. - -## Running the `ifacialmocap_poser` - -First, run iFacialMocap on your iOS device. It should show you the device's IP address. Jot it down. Keep the app open. - -![IP address in iFacialMocap screen](docs/ifacialmocap_ip.jpg "IP address in iFacialMocap screen") - -Open a shell. Activate the Python environment. Change your working directory to the repository's root directory. Then, run: - -``` -> python tha3/app/ifacialmocap_puppeteer.py -``` - -You will see a text box with label "Capture Device IP." Write the iOS device's IP address that you jotted down there. - -![Write IP address of your iOS device in the 'Capture Device IP' text box.](docs/ifacialmocap_puppeteer_ip_address_box.png "Write IP address of your iOS device in the 'Capture Device IP' text box.") - -Click the "START CAPTURE!" button to the right. - -![Click the 'START CAPTURE!' button.](docs/ifacialmocap_puppeteer_click_start_capture.png "Click the 'START CAPTURE!' button.") - -If the programs are connected properly, you should see the numbers in the bottom part of the window change when you move your head. - -![The numbers in the bottom part of the window should change when you move your head.](docs/ifacialmocap_puppeteer_numbers.png "The numbers in the bottom part of the window should change when you move your head.") - -Now, you can load an image of a character, and it should follow your facial movement. - -## Contraints on Input Images - -In order for the system to work well, the input image must obey the following constraints: - -* It should be of resolution 512 x 512. (If the demo programs receives an input image of any other size, they will resize the image to this resolution and also output at this resolution.) -* It must have an alpha channel. -* It must contain only one humanoid character. -* The character should be standing upright and facing forward. -* The character's hands should be below and far from the head. -* The head of the character should roughly be contained in the 128 x 128 box in the middle of the top half of the image. -* The alpha channels of all pixels that do not belong to the character (i.e., background pixels) must be 0. - -![An example of an image that conforms to the above criteria](docs/input_spec.png "An example of an image that conforms to the above criteria") - -See the project's [write-up](http://pkhungurn.github.io/talking-head-anime-3/full.html#sec:problem-spec) for more details on the input image. - -## Citation - -If your academic work benefits from the code in this repository, please cite the project's web page as follows: - -> Pramook Khungurn. **Talking Head(?) Anime from a Single Image 3: Now the Body Too.** http://pkhungurn.github.io/talking-head-anime-3/, 2022. Accessed: YYYY-MM-DD. - -You can also used the following BibTex entry: - -``` -@misc{Khungurn:2022, - author = {Pramook Khungurn}, - title = {Talking Head(?) Anime from a Single Image 3: Now the Body Too}, - howpublished = {\url{http://pkhungurn.github.io/talking-head-anime-3/}}, - year = 2022, - note = {Accessed: YYYY-MM-DD}, -} -``` - -## Disclaimer - -While the author is an employee of [Google Japan](https://careers.google.com/locations/tokyo/), this software is not Google's product and is not supported by Google. - -The copyright of this software belongs to me as I have requested it using the [IARC process](https://opensource.google/documentation/reference/releasing#iarc). However, Google might claim the rights to the intellectual -property of this invention. - -The code is released under the [MIT license](https://github.com/pkhungurn/talking-head-anime-2-demo/blob/master/LICENSE). -The model is released under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/legalcode). Please see the README.md file in the ``data/images`` directory for the licenses for the images there. diff --git a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/utils/utils_os.py b/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/utils/utils_os.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/datasciencedojo/Transcription/app.py b/spaces/datasciencedojo/Transcription/app.py deleted file mode 100644 index 53d05efd09aab6e3c3d4aef728a7763285fd7d22..0000000000000000000000000000000000000000 --- a/spaces/datasciencedojo/Transcription/app.py +++ /dev/null @@ -1,80 +0,0 @@ -import gradio as gr -import nemo.collections.asr as nemo_asr - -asr_model = nemo_asr.models.ASRModel.from_pretrained("nvidia/stt_en_conformer_ctc_large") - -def transcription(audio): - return asr_model.transcribe([audio.name])[0] - -examples = [ - ['TestAudio1.mp3'] -] - -css = """ -footer {display:none !important} -.output-markdown{display:none !important} -.gr-button-primary { - z-index: 14; - height: 43px; - width: 130px; - left: 0px; - top: 0px; - padding: 0px; - cursor: pointer !important; - background: none rgb(17, 20, 45) !important; - border: none !important; - text-align: center !important; - font-family: Poppins !important; - font-size: 14px !important; - font-weight: 500 !important; - color: rgb(255, 255, 255) !important; - line-height: 1 !important; - border-radius: 12px !important; - transition: box-shadow 200ms ease 0s, background 200ms ease 0s !important; - box-shadow: none !important; -} -.gr-button-primary:hover{ - z-index: 14; - height: 43px; - width: 130px; - left: 0px; - top: 0px; - padding: 0px; - cursor: pointer !important; - background: none rgb(37, 56, 133) !important; - border: none !important; - text-align: center !important; - font-family: Poppins !important; - font-size: 14px !important; - font-weight: 500 !important; - color: rgb(255, 255, 255) !important; - line-height: 1 !important; - border-radius: 12px !important; - transition: box-shadow 200ms ease 0s, background 200ms ease 0s !important; - box-shadow: rgb(0 0 0 / 23%) 0px 1px 7px 0px !important; -} -.hover\:bg-orange-50:hover { - --tw-bg-opacity: 1 !important; - background-color: rgb(229,225,255) !important; -} -.to-orange-200 { - --tw-gradient-to: rgb(37 56 133 / 37%) !important; -} -.from-orange-400 { - --tw-gradient-from: rgb(17, 20, 45) !important; - --tw-gradient-to: rgb(255 150 51 / 0); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to) !important; -} -.group-hover\:from-orange-500{ - --tw-gradient-from:rgb(17, 20, 45) !important; - --tw-gradient-to: rgb(37 56 133 / 37%); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to) !important; -} -.group:hover .group-hover\:text-orange-500{ - --tw-text-opacity: 1 !important; - color:rgb(37 56 133 / var(--tw-text-opacity)) !important; -} -""" - -demo = gr.Interface(fn = transcription, inputs = gr.inputs.Audio(label="Input Audio", type="file"), outputs = gr.outputs.Textbox(label="Transcription"), title="Audio Transcription | Data Science Dojo", examples = examples, css = css) -demo.launch() \ No newline at end of file diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I_J_.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I_J_.py deleted file mode 100644 index bc8fe92aac9d18bfd5ee565588d8cebf7d00afd1..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/T_S_I_J_.py +++ /dev/null @@ -1,5 +0,0 @@ -from .T_S_I_V_ import table_T_S_I_V_ - - -class table_T_S_I_J_(table_T_S_I_V_): - pass diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/varLib/instancer/__init__.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/varLib/instancer/__init__.py deleted file mode 100644 index a8663ec42247a7967675755090b34cec2e9e2cd8..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/varLib/instancer/__init__.py +++ /dev/null @@ -1,1508 +0,0 @@ -""" Partially instantiate a variable font. - -The module exports an `instantiateVariableFont` function and CLI that allow to -create full instances (i.e. static fonts) from variable fonts, as well as "partial" -variable fonts that only contain a subset of the original variation space. - -For example, if you wish to pin the width axis to a given location while also -restricting the weight axis to 400..700 range, you can do:: - - $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700 - -See `fonttools varLib.instancer --help` for more info on the CLI options. - -The module's entry point is the `instantiateVariableFont` function, which takes -a TTFont object and a dict specifying either axis coodinates or (min, max) ranges, -and returns a new TTFont representing either a partial VF, or full instance if all -the VF axes were given an explicit coordinate. - -E.g. here's how to pin the wght axis at a given location in a wght+wdth variable -font, keeping only the deltas associated with the wdth axis:: - -| >>> from fontTools import ttLib -| >>> from fontTools.varLib import instancer -| >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf") -| >>> [a.axisTag for a in varfont["fvar"].axes] # the varfont's current axes -| ['wght', 'wdth'] -| >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300}) -| >>> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght' -| ['wdth'] - -If the input location specifies all the axes, the resulting instance is no longer -'variable' (same as using fontools varLib.mutator): - -| >>> instance = instancer.instantiateVariableFont( -| ... varfont, {"wght": 700, "wdth": 67.5} -| ... ) -| >>> "fvar" not in instance -| True - -If one just want to drop an axis at the default location, without knowing in -advance what the default value for that axis is, one can pass a `None` value: - -| >>> instance = instancer.instantiateVariableFont(varfont, {"wght": None}) -| >>> len(varfont["fvar"].axes) -| 1 - -From the console script, this is equivalent to passing `wght=drop` as input. - -This module is similar to fontTools.varLib.mutator, which it's intended to supersede. -Note that, unlike varLib.mutator, when an axis is not mentioned in the input -location, the varLib.instancer will keep the axis and the corresponding deltas, -whereas mutator implicitly drops the axis at its default coordinate. - -The module supports all the following "levels" of instancing, which can of -course be combined: - -L1 - dropping one or more axes while leaving the default tables unmodified; - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": None}) - -L2 - dropping one or more axes while pinning them at non-default locations; - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": 700}) - -L3 - restricting the range of variation of one or more axes, by setting either - a new minimum or maximum, potentially -- though not necessarily -- dropping - entire regions of variations that fall completely outside this new range. - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)}) - -L4 - moving the default location of an axis, by specifying (min,defalt,max) values: - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)}) - -Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table) -are supported, but support for CFF2 variable fonts will be added soon. - -The discussion and implementation of these features are tracked at -https://github.com/fonttools/fonttools/issues/1537 -""" -from fontTools.misc.fixedTools import ( - floatToFixedToFloat, - strToFixedToFloat, - otRound, -) -from fontTools.varLib.models import supportScalar, normalizeValue, piecewiseLinearMap -from fontTools.ttLib import TTFont -from fontTools.ttLib.tables.TupleVariation import TupleVariation -from fontTools.ttLib.tables import _g_l_y_f -from fontTools import varLib - -# we import the `subset` module because we use the `prune_lookups` method on the GSUB -# table class, and that method is only defined dynamically upon importing `subset` -from fontTools import subset # noqa: F401 -from fontTools.varLib import builder -from fontTools.varLib.mvar import MVAR_ENTRIES -from fontTools.varLib.merger import MutatorMerger -from fontTools.varLib.instancer import names -from .featureVars import instantiateFeatureVariations -from fontTools.misc.cliTools import makeOutputFileName -from fontTools.varLib.instancer import solver -import collections -import dataclasses -from copy import deepcopy -from enum import IntEnum -import logging -import os -import re -from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union -import warnings - - -log = logging.getLogger("fontTools.varLib.instancer") - - -def AxisRange(minimum, maximum): - warnings.warn( - "AxisRange is deprecated; use AxisTriple instead", - DeprecationWarning, - stacklevel=2, - ) - return AxisTriple(minimum, None, maximum) - - -def NormalizedAxisRange(minimum, maximum): - warnings.warn( - "NormalizedAxisRange is deprecated; use AxisTriple instead", - DeprecationWarning, - stacklevel=2, - ) - return NormalizedAxisTriple(minimum, None, maximum) - - -@dataclasses.dataclass(frozen=True, order=True, repr=False) -class AxisTriple(Sequence): - """A triple of (min, default, max) axis values. - - The default value can be None, in which case the limitRangeAndPopulateDefault() - method can be used to fill in the missing default value based on the fvar axis - default. - """ - - minimum: float - default: Optional[float] # if None, filled with by limitRangeAndPopulateDefault - maximum: float - - def __post_init__(self): - if self.default is None and self.minimum == self.maximum: - object.__setattr__(self, "default", self.minimum) - if not ( - (self.minimum <= self.default <= self.maximum) - if self.default is not None - else (self.minimum <= self.maximum) - ): - raise ValueError( - f"{type(self).__name__} minimum ({self.minimum}) must be <= default " - f"({self.default}) which must be <= maximum ({self.maximum})" - ) - - def __getitem__(self, i): - fields = dataclasses.fields(self) - return getattr(self, fields[i].name) - - def __len__(self): - return len(dataclasses.fields(self)) - - def _replace(self, **kwargs): - return dataclasses.replace(self, **kwargs) - - def __repr__(self): - return ( - f"({', '.join(format(v, 'g') if v is not None else 'None' for v in self)})" - ) - - @classmethod - def expand( - cls, - v: Union[ - "AxisTriple", - float, # pin axis at single value, same as min==default==max - Tuple[float, float], # (min, max), restrict axis and keep default - Tuple[float, float, float], # (min, default, max) - ], - ) -> "AxisTriple": - """Convert a single value or a tuple into an AxisTriple. - - If the input is a single value, it is interpreted as a pin at that value. - If the input is a tuple, it is interpreted as (min, max) or (min, default, max). - """ - if isinstance(v, cls): - return v - if isinstance(v, (int, float)): - return cls(v, v, v) - try: - n = len(v) - except TypeError as e: - raise ValueError( - f"expected float, 2- or 3-tuple of floats; got {type(v)}: {v!r}" - ) from e - default = None - if n == 2: - minimum, maximum = v - elif n >= 3: - return cls(*v) - else: - raise ValueError(f"expected sequence of 2 or 3; got {n}: {v!r}") - return cls(minimum, default, maximum) - - def limitRangeAndPopulateDefault(self, fvarTriple) -> "AxisTriple": - """Return a new AxisTriple with the default value filled in. - - Set default to fvar axis default if the latter is within the min/max range, - otherwise set default to the min or max value, whichever is closer to the - fvar axis default. - If the default value is already set, return self. - """ - minimum = self.minimum - maximum = self.maximum - default = self.default - if default is None: - default = fvarTriple[1] - - minimum = max(self.minimum, fvarTriple[0]) - maximum = max(self.maximum, fvarTriple[0]) - minimum = min(minimum, fvarTriple[2]) - maximum = min(maximum, fvarTriple[2]) - default = max(minimum, min(maximum, default)) - - return AxisTriple(minimum, default, maximum) - - -@dataclasses.dataclass(frozen=True, order=True, repr=False) -class NormalizedAxisTriple(AxisTriple): - """A triple of (min, default, max) normalized axis values.""" - - minimum: float - default: float - maximum: float - - def __post_init__(self): - if self.default is None: - object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0))) - if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0): - raise ValueError( - "Normalized axis values not in -1..+1 range; got " - f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})" - ) - - -@dataclasses.dataclass(frozen=True, order=True, repr=False) -class NormalizedAxisTripleAndDistances(AxisTriple): - """A triple of (min, default, max) normalized axis values, - with distances between min and default, and default and max, - in the *pre-normalized* space.""" - - minimum: float - default: float - maximum: float - distanceNegative: Optional[float] = 1 - distancePositive: Optional[float] = 1 - - def __post_init__(self): - if self.default is None: - object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0))) - if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0): - raise ValueError( - "Normalized axis values not in -1..+1 range; got " - f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})" - ) - - def reverse_negate(self): - v = self - return self.__class__(-v[2], -v[1], -v[0], v[4], v[3]) - - def renormalizeValue(self, v, extrapolate=True): - """Renormalizes a normalized value v to the range of this axis, - considering the pre-normalized distances as well as the new - axis limits.""" - - lower, default, upper, distanceNegative, distancePositive = self - assert lower <= default <= upper - - if not extrapolate: - v = max(lower, min(upper, v)) - - if v == default: - return 0 - - if default < 0: - return -self.reverse_negate().renormalizeValue(-v, extrapolate=extrapolate) - - # default >= 0 and v != default - - if v > default: - return (v - default) / (upper - default) - - # v < default - - if lower >= 0: - return (v - default) / (default - lower) - - # lower < 0 and v < default - - totalDistance = distanceNegative * -lower + distancePositive * default - - if v >= 0: - vDistance = (default - v) * distancePositive - else: - vDistance = -v * distanceNegative + distancePositive * default - - return -vDistance / totalDistance - - -class _BaseAxisLimits(Mapping[str, AxisTriple]): - def __getitem__(self, key: str) -> AxisTriple: - return self._data[key] - - def __iter__(self) -> Iterable[str]: - return iter(self._data) - - def __len__(self) -> int: - return len(self._data) - - def __repr__(self) -> str: - return f"{type(self).__name__}({self._data!r})" - - def __str__(self) -> str: - return str(self._data) - - def defaultLocation(self) -> Dict[str, float]: - """Return a dict of default axis values.""" - return {k: v.default for k, v in self.items()} - - def pinnedLocation(self) -> Dict[str, float]: - """Return a location dict with only the pinned axes.""" - return {k: v.default for k, v in self.items() if v.minimum == v.maximum} - - -class AxisLimits(_BaseAxisLimits): - """Maps axis tags (str) to AxisTriple values.""" - - def __init__(self, *args, **kwargs): - self._data = data = {} - for k, v in dict(*args, **kwargs).items(): - if v is None: - # will be filled in by limitAxesAndPopulateDefaults - data[k] = v - else: - try: - triple = AxisTriple.expand(v) - except ValueError as e: - raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e - data[k] = triple - - def limitAxesAndPopulateDefaults(self, varfont) -> "AxisLimits": - """Return a new AxisLimits with defaults filled in from fvar table. - - If all axis limits already have defaults, return self. - """ - fvar = varfont["fvar"] - fvarTriples = { - a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes - } - newLimits = {} - for axisTag, triple in self.items(): - fvarTriple = fvarTriples[axisTag] - default = fvarTriple[1] - if triple is None: - newLimits[axisTag] = AxisTriple(default, default, default) - else: - newLimits[axisTag] = triple.limitRangeAndPopulateDefault(fvarTriple) - return type(self)(newLimits) - - def normalize(self, varfont, usingAvar=True) -> "NormalizedAxisLimits": - """Return a new NormalizedAxisLimits with normalized -1..0..+1 values. - - If usingAvar is True, the avar table is used to warp the default normalization. - """ - fvar = varfont["fvar"] - badLimits = set(self.keys()).difference(a.axisTag for a in fvar.axes) - if badLimits: - raise ValueError("Cannot limit: {} not present in fvar".format(badLimits)) - - axes = { - a.axisTag: (a.minValue, a.defaultValue, a.maxValue) - for a in fvar.axes - if a.axisTag in self - } - - avarSegments = {} - if usingAvar and "avar" in varfont: - avarSegments = varfont["avar"].segments - - normalizedLimits = {} - - for axis_tag, triple in axes.items(): - distanceNegative = triple[1] - triple[0] - distancePositive = triple[2] - triple[1] - - if self[axis_tag] is None: - normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances( - 0, 0, 0, distanceNegative, distancePositive - ) - continue - - minV, defaultV, maxV = self[axis_tag] - - if defaultV is None: - defaultV = triple[1] - - avarMapping = avarSegments.get(axis_tag, None) - normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances( - *(normalize(v, triple, avarMapping) for v in (minV, defaultV, maxV)), - distanceNegative, - distancePositive, - ) - - return NormalizedAxisLimits(normalizedLimits) - - -class NormalizedAxisLimits(_BaseAxisLimits): - """Maps axis tags (str) to NormalizedAxisTriple values.""" - - def __init__(self, *args, **kwargs): - self._data = data = {} - for k, v in dict(*args, **kwargs).items(): - try: - triple = NormalizedAxisTripleAndDistances.expand(v) - except ValueError as e: - raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e - data[k] = triple - - -class OverlapMode(IntEnum): - KEEP_AND_DONT_SET_FLAGS = 0 - KEEP_AND_SET_FLAGS = 1 - REMOVE = 2 - REMOVE_AND_IGNORE_ERRORS = 3 - - -def instantiateTupleVariationStore( - variations, axisLimits, origCoords=None, endPts=None -): - """Instantiate TupleVariation list at the given location, or limit axes' min/max. - - The 'variations' list of TupleVariation objects is modified in-place. - The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples - specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes - have minimum == default == maximum. - - A 'full' instance (i.e. static font) is produced when all the axes are pinned to - single coordinates; a 'partial' instance (i.e. a less variable font) is produced - when some of the axes are omitted, or restricted with a new range. - - Tuples that do not participate are kept as they are. Those that have 0 influence - at the given location are removed from the variation store. - Those that are fully instantiated (i.e. all their axes are being pinned) are also - removed from the variation store, their scaled deltas accummulated and returned, so - that they can be added by the caller to the default instance's coordinates. - Tuples that are only partially instantiated (i.e. not all the axes that they - participate in are being pinned) are kept in the store, and their deltas multiplied - by the scalar support of the axes to be pinned at the desired location. - - Args: - variations: List[TupleVariation] from either 'gvar' or 'cvar'. - axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max) - normalized coordinates for the full or partial instance. - origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar' - inferred points (cf. table__g_l_y_f._getCoordinatesAndControls). - endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas. - - Returns: - List[float]: the overall delta adjustment after applicable deltas were summed. - """ - - newVariations = changeTupleVariationsAxisLimits(variations, axisLimits) - - mergedVariations = collections.OrderedDict() - for var in newVariations: - # compute inferred deltas only for gvar ('origCoords' is None for cvar) - if origCoords is not None: - var.calcInferredDeltas(origCoords, endPts) - - # merge TupleVariations with overlapping "tents" - axes = frozenset(var.axes.items()) - if axes in mergedVariations: - mergedVariations[axes] += var - else: - mergedVariations[axes] = var - - # drop TupleVariation if all axes have been pinned (var.axes.items() is empty); - # its deltas will be added to the default instance's coordinates - defaultVar = mergedVariations.pop(frozenset(), None) - - for var in mergedVariations.values(): - var.roundDeltas() - variations[:] = list(mergedVariations.values()) - - return defaultVar.coordinates if defaultVar is not None else [] - - -def changeTupleVariationsAxisLimits(variations, axisLimits): - for axisTag, axisLimit in sorted(axisLimits.items()): - newVariations = [] - for var in variations: - newVariations.extend(changeTupleVariationAxisLimit(var, axisTag, axisLimit)) - variations = newVariations - return variations - - -def changeTupleVariationAxisLimit(var, axisTag, axisLimit): - assert isinstance(axisLimit, NormalizedAxisTripleAndDistances) - - # Skip when current axis is missing (i.e. doesn't participate), - lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1)) - if peak == 0: - return [var] - # Drop if the var 'tent' isn't well-formed - if not (lower <= peak <= upper) or (lower < 0 and upper > 0): - return [] - - if axisTag not in var.axes: - return [var] - - tent = var.axes[axisTag] - - solutions = solver.rebaseTent(tent, axisLimit) - - out = [] - for scalar, tent in solutions: - newVar = ( - TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var - ) - if tent is None: - newVar.axes.pop(axisTag) - else: - assert tent[1] != 0, tent - newVar.axes[axisTag] = tent - newVar *= scalar - out.append(newVar) - - return out - - -def _instantiateGvarGlyph( - glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True -): - coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics) - endPts = ctrl.endPts - - # Not every glyph may have variations - tupleVarStore = gvar.variations.get(glyphname) - - if tupleVarStore: - defaultDeltas = instantiateTupleVariationStore( - tupleVarStore, axisLimits, coordinates, endPts - ) - - if defaultDeltas: - coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas) - - glyph = glyf[glyphname] - if glyph.isVarComposite(): - for component in glyph.components: - newLocation = {} - for tag, loc in component.location.items(): - if tag not in axisLimits: - newLocation[tag] = loc - continue - if component.flags & _g_l_y_f.VarComponentFlags.AXES_HAVE_VARIATION: - raise NotImplementedError( - "Instancing accross VarComposite axes with variation is not supported." - ) - limits = axisLimits[tag] - loc = limits.renormalizeValue(loc, extrapolate=False) - newLocation[tag] = loc - component.location = newLocation - - # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from - # the four phantom points and glyph bounding boxes. - # We call it unconditionally even if a glyph has no variations or no deltas are - # applied at this location, in case the glyph's xMin and in turn its sidebearing - # have changed. E.g. a composite glyph has no deltas for the component's (x, y) - # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in - # gvar table is empty; however, the composite's base glyph may have deltas - # applied, hence the composite's bbox and left/top sidebearings may need updating - # in the instanced font. - glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics) - - if not tupleVarStore: - if glyphname in gvar.variations: - del gvar.variations[glyphname] - return - - if optimize: - isComposite = glyf[glyphname].isComposite() - for var in tupleVarStore: - var.optimize(coordinates, endPts, isComposite) - - -def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True): - """Remove? - https://github.com/fonttools/fonttools/pull/2266""" - gvar = varfont["gvar"] - glyf = varfont["glyf"] - hMetrics = varfont["hmtx"].metrics - vMetrics = getattr(varfont.get("vmtx"), "metrics", None) - _instantiateGvarGlyph( - glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize - ) - - -def instantiateGvar(varfont, axisLimits, optimize=True): - log.info("Instantiating glyf/gvar tables") - - gvar = varfont["gvar"] - glyf = varfont["glyf"] - hMetrics = varfont["hmtx"].metrics - vMetrics = getattr(varfont.get("vmtx"), "metrics", None) - # Get list of glyph names sorted by component depth. - # If a composite glyph is processed before its base glyph, the bounds may - # be calculated incorrectly because deltas haven't been applied to the - # base glyph yet. - glyphnames = sorted( - glyf.glyphOrder, - key=lambda name: ( - glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth - if glyf[name].isComposite() or glyf[name].isVarComposite() - else 0, - name, - ), - ) - for glyphname in glyphnames: - _instantiateGvarGlyph( - glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize - ) - - if not gvar.variations: - del varfont["gvar"] - - -def setCvarDeltas(cvt, deltas): - for i, delta in enumerate(deltas): - if delta: - cvt[i] += otRound(delta) - - -def instantiateCvar(varfont, axisLimits): - log.info("Instantiating cvt/cvar tables") - - cvar = varfont["cvar"] - - defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits) - - if defaultDeltas: - setCvarDeltas(varfont["cvt "], defaultDeltas) - - if not cvar.variations: - del varfont["cvar"] - - -def setMvarDeltas(varfont, deltas): - mvar = varfont["MVAR"].table - records = mvar.ValueRecord - for rec in records: - mvarTag = rec.ValueTag - if mvarTag not in MVAR_ENTRIES: - continue - tableTag, itemName = MVAR_ENTRIES[mvarTag] - delta = deltas[rec.VarIdx] - if delta != 0: - setattr( - varfont[tableTag], - itemName, - getattr(varfont[tableTag], itemName) + otRound(delta), - ) - - -def instantiateMVAR(varfont, axisLimits): - log.info("Instantiating MVAR table") - - mvar = varfont["MVAR"].table - fvarAxes = varfont["fvar"].axes - varStore = mvar.VarStore - defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) - setMvarDeltas(varfont, defaultDeltas) - - if varStore.VarRegionList.Region: - varIndexMapping = varStore.optimize() - for rec in mvar.ValueRecord: - rec.VarIdx = varIndexMapping[rec.VarIdx] - else: - del varfont["MVAR"] - - -def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder): - oldMapping = getattr(table, attrName).mapping - newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder] - setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder)) - - -# TODO(anthrotype) Add support for HVAR/VVAR in CFF2 -def _instantiateVHVAR(varfont, axisLimits, tableFields): - location = axisLimits.pinnedLocation() - tableTag = tableFields.tableTag - fvarAxes = varfont["fvar"].axes - # Deltas from gvar table have already been applied to the hmtx/vmtx. For full - # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return - if set(location).issuperset(axis.axisTag for axis in fvarAxes): - log.info("Dropping %s table", tableTag) - del varfont[tableTag] - return - - log.info("Instantiating %s table", tableTag) - vhvar = varfont[tableTag].table - varStore = vhvar.VarStore - # since deltas were already applied, the return value here is ignored - instantiateItemVariationStore(varStore, fvarAxes, axisLimits) - - if varStore.VarRegionList.Region: - # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap - # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is - # used for advances, skip re-optimizing and maintain original VariationIndex. - if getattr(vhvar, tableFields.advMapping): - varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False) - glyphOrder = varfont.getGlyphOrder() - _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder) - if getattr(vhvar, tableFields.sb1): # left or top sidebearings - _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder) - if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings - _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder) - if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping): - _remapVarIdxMap( - vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder - ) - - -def instantiateHVAR(varfont, axisLimits): - return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS) - - -def instantiateVVAR(varfont, axisLimits): - return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS) - - -class _TupleVarStoreAdapter(object): - def __init__(self, regions, axisOrder, tupleVarData, itemCounts): - self.regions = regions - self.axisOrder = axisOrder - self.tupleVarData = tupleVarData - self.itemCounts = itemCounts - - @classmethod - def fromItemVarStore(cls, itemVarStore, fvarAxes): - axisOrder = [axis.axisTag for axis in fvarAxes] - regions = [ - region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region - ] - tupleVarData = [] - itemCounts = [] - for varData in itemVarStore.VarData: - variations = [] - varDataRegions = (regions[i] for i in varData.VarRegionIndex) - for axes, coordinates in zip(varDataRegions, zip(*varData.Item)): - variations.append(TupleVariation(axes, list(coordinates))) - tupleVarData.append(variations) - itemCounts.append(varData.ItemCount) - return cls(regions, axisOrder, tupleVarData, itemCounts) - - def rebuildRegions(self): - # Collect the set of all unique region axes from the current TupleVariations. - # We use an OrderedDict to de-duplicate regions while keeping the order. - uniqueRegions = collections.OrderedDict.fromkeys( - ( - frozenset(var.axes.items()) - for variations in self.tupleVarData - for var in variations - ) - ) - # Maintain the original order for the regions that pre-existed, appending - # the new regions at the end of the region list. - newRegions = [] - for region in self.regions: - regionAxes = frozenset(region.items()) - if regionAxes in uniqueRegions: - newRegions.append(region) - del uniqueRegions[regionAxes] - if uniqueRegions: - newRegions.extend(dict(region) for region in uniqueRegions) - self.regions = newRegions - - def instantiate(self, axisLimits): - defaultDeltaArray = [] - for variations, itemCount in zip(self.tupleVarData, self.itemCounts): - defaultDeltas = instantiateTupleVariationStore(variations, axisLimits) - if not defaultDeltas: - defaultDeltas = [0] * itemCount - defaultDeltaArray.append(defaultDeltas) - - # rebuild regions whose axes were dropped or limited - self.rebuildRegions() - - pinnedAxes = set(axisLimits.pinnedLocation()) - self.axisOrder = [ - axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes - ] - - return defaultDeltaArray - - def asItemVarStore(self): - regionOrder = [frozenset(axes.items()) for axes in self.regions] - varDatas = [] - for variations, itemCount in zip(self.tupleVarData, self.itemCounts): - if variations: - assert len(variations[0].coordinates) == itemCount - varRegionIndices = [ - regionOrder.index(frozenset(var.axes.items())) for var in variations - ] - varDataItems = list(zip(*(var.coordinates for var in variations))) - varDatas.append( - builder.buildVarData(varRegionIndices, varDataItems, optimize=False) - ) - else: - varDatas.append( - builder.buildVarData([], [[] for _ in range(itemCount)]) - ) - regionList = builder.buildVarRegionList(self.regions, self.axisOrder) - itemVarStore = builder.buildVarStore(regionList, varDatas) - # remove unused regions from VarRegionList - itemVarStore.prune_regions() - return itemVarStore - - -def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits): - """Compute deltas at partial location, and update varStore in-place. - - Remove regions in which all axes were instanced, or fall outside the new axis - limits. Scale the deltas of the remaining regions where only some of the axes - were instanced. - - The number of VarData subtables, and the number of items within each, are - not modified, in order to keep the existing VariationIndex valid. - One may call VarStore.optimize() method after this to further optimize those. - - Args: - varStore: An otTables.VarStore object (Item Variation Store) - fvarAxes: list of fvar's Axis objects - axisLimits: NormalizedAxisLimits: mapping axis tags to normalized - min/default/max axis coordinates. May not specify coordinates/ranges for - all the fvar axes. - - Returns: - defaultDeltas: to be added to the default instance, of type dict of floats - keyed by VariationIndex compound values: i.e. (outer << 16) + inner. - """ - tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes) - defaultDeltaArray = tupleVarStore.instantiate(axisLimits) - newItemVarStore = tupleVarStore.asItemVarStore() - - itemVarStore.VarRegionList = newItemVarStore.VarRegionList - assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount - itemVarStore.VarData = newItemVarStore.VarData - - defaultDeltas = { - ((major << 16) + minor): delta - for major, deltas in enumerate(defaultDeltaArray) - for minor, delta in enumerate(deltas) - } - defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0 - return defaultDeltas - - -def instantiateOTL(varfont, axisLimits): - # TODO(anthrotype) Support partial instancing of JSTF and BASE tables - - if ( - "GDEF" not in varfont - or varfont["GDEF"].table.Version < 0x00010003 - or not varfont["GDEF"].table.VarStore - ): - return - - if "GPOS" in varfont: - msg = "Instantiating GDEF and GPOS tables" - else: - msg = "Instantiating GDEF table" - log.info(msg) - - gdef = varfont["GDEF"].table - varStore = gdef.VarStore - fvarAxes = varfont["fvar"].axes - - defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) - - # When VF are built, big lookups may overflow and be broken into multiple - # subtables. MutatorMerger (which inherits from AligningMerger) reattaches - # them upon instancing, in case they can now fit a single subtable (if not, - # they will be split again upon compilation). - # This 'merger' also works as a 'visitor' that traverses the OTL tables and - # calls specific methods when instances of a given type are found. - # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF - # LigatureCarets, and optionally deletes all VariationIndex tables if the - # VarStore is fully instanced. - merger = MutatorMerger( - varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region) - ) - merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"]) - - if varStore.VarRegionList.Region: - varIndexMapping = varStore.optimize() - gdef.remap_device_varidxes(varIndexMapping) - if "GPOS" in varfont: - varfont["GPOS"].table.remap_device_varidxes(varIndexMapping) - else: - # Downgrade GDEF. - del gdef.VarStore - gdef.Version = 0x00010002 - if gdef.MarkGlyphSetsDef is None: - del gdef.MarkGlyphSetsDef - gdef.Version = 0x00010000 - - if not ( - gdef.LigCaretList - or gdef.MarkAttachClassDef - or gdef.GlyphClassDef - or gdef.AttachList - or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef) - ): - del varfont["GDEF"] - - -def _isValidAvarSegmentMap(axisTag, segmentMap): - if not segmentMap: - return True - if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()): - log.warning( - f"Invalid avar SegmentMap record for axis '{axisTag}': does not " - "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}" - ) - return False - previousValue = None - for fromCoord, toCoord in sorted(segmentMap.items()): - if previousValue is not None and previousValue > toCoord: - log.warning( - f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record " - f"for axis '{axisTag}': the toCoordinate value must be >= to " - f"the toCoordinate value of the preceding record ({previousValue})." - ) - return False - previousValue = toCoord - return True - - -def instantiateAvar(varfont, axisLimits): - # 'axisLimits' dict must contain user-space (non-normalized) coordinates. - - segments = varfont["avar"].segments - - # drop table if we instantiate all the axes - pinnedAxes = set(axisLimits.pinnedLocation()) - if pinnedAxes.issuperset(segments): - log.info("Dropping avar table") - del varfont["avar"] - return - - log.info("Instantiating avar table") - for axis in pinnedAxes: - if axis in segments: - del segments[axis] - - # First compute the default normalization for axisLimits coordinates: i.e. - # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly, - # without using the avar table's mappings. - # Then, for each SegmentMap, if we are restricting its axis, compute the new - # mappings by dividing the key/value pairs by the desired new min/max values, - # dropping any mappings that fall outside the restricted range. - # The keys ('fromCoord') are specified in default normalized coordinate space, - # whereas the values ('toCoord') are "mapped forward" using the SegmentMap. - normalizedRanges = axisLimits.normalize(varfont, usingAvar=False) - newSegments = {} - for axisTag, mapping in segments.items(): - if not _isValidAvarSegmentMap(axisTag, mapping): - continue - if mapping and axisTag in normalizedRanges: - axisRange = normalizedRanges[axisTag] - mappedMin = floatToFixedToFloat( - piecewiseLinearMap(axisRange.minimum, mapping), 14 - ) - mappedDef = floatToFixedToFloat( - piecewiseLinearMap(axisRange.default, mapping), 14 - ) - mappedMax = floatToFixedToFloat( - piecewiseLinearMap(axisRange.maximum, mapping), 14 - ) - mappedAxisLimit = NormalizedAxisTripleAndDistances( - mappedMin, - mappedDef, - mappedMax, - axisRange.distanceNegative, - axisRange.distancePositive, - ) - newMapping = {} - for fromCoord, toCoord in mapping.items(): - if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum: - continue - fromCoord = axisRange.renormalizeValue(fromCoord) - - assert mappedMin <= toCoord <= mappedMax - toCoord = mappedAxisLimit.renormalizeValue(toCoord) - - fromCoord = floatToFixedToFloat(fromCoord, 14) - toCoord = floatToFixedToFloat(toCoord, 14) - newMapping[fromCoord] = toCoord - newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}) - newSegments[axisTag] = newMapping - else: - newSegments[axisTag] = mapping - varfont["avar"].segments = newSegments - - -def isInstanceWithinAxisRanges(location, axisRanges): - for axisTag, coord in location.items(): - if axisTag in axisRanges: - axisRange = axisRanges[axisTag] - if coord < axisRange.minimum or coord > axisRange.maximum: - return False - return True - - -def instantiateFvar(varfont, axisLimits): - # 'axisLimits' dict must contain user-space (non-normalized) coordinates - - location = axisLimits.pinnedLocation() - - fvar = varfont["fvar"] - - # drop table if we instantiate all the axes - if set(location).issuperset(axis.axisTag for axis in fvar.axes): - log.info("Dropping fvar table") - del varfont["fvar"] - return - - log.info("Instantiating fvar table") - - axes = [] - for axis in fvar.axes: - axisTag = axis.axisTag - if axisTag in location: - continue - if axisTag in axisLimits: - triple = axisLimits[axisTag] - if triple.default is None: - triple = (triple.minimum, axis.defaultValue, triple.maximum) - axis.minValue, axis.defaultValue, axis.maxValue = triple - axes.append(axis) - fvar.axes = axes - - # only keep NamedInstances whose coordinates == pinned axis location - instances = [] - for instance in fvar.instances: - if any(instance.coordinates[axis] != value for axis, value in location.items()): - continue - for axisTag in location: - del instance.coordinates[axisTag] - if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits): - continue - instances.append(instance) - fvar.instances = instances - - -def instantiateSTAT(varfont, axisLimits): - # 'axisLimits' dict must contain user-space (non-normalized) coordinates - - stat = varfont["STAT"].table - if not stat.DesignAxisRecord or not ( - stat.AxisValueArray and stat.AxisValueArray.AxisValue - ): - return # STAT table empty, nothing to do - - log.info("Instantiating STAT table") - newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits) - stat.AxisValueCount = len(newAxisValueTables) - if stat.AxisValueCount: - stat.AxisValueArray.AxisValue = newAxisValueTables - else: - stat.AxisValueArray = None - - -def axisValuesFromAxisLimits(stat, axisLimits): - def isAxisValueOutsideLimits(axisTag, axisValue): - if axisTag in axisLimits: - triple = axisLimits[axisTag] - if axisValue < triple.minimum or axisValue > triple.maximum: - return True - return False - - # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the - # exact (nominal) value, or is restricted but the value is within the new range - designAxes = stat.DesignAxisRecord.Axis - newAxisValueTables = [] - for axisValueTable in stat.AxisValueArray.AxisValue: - axisValueFormat = axisValueTable.Format - if axisValueFormat in (1, 2, 3): - axisTag = designAxes[axisValueTable.AxisIndex].AxisTag - if axisValueFormat == 2: - axisValue = axisValueTable.NominalValue - else: - axisValue = axisValueTable.Value - if isAxisValueOutsideLimits(axisTag, axisValue): - continue - elif axisValueFormat == 4: - # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match - # the pinned location or is outside range - dropAxisValueTable = False - for rec in axisValueTable.AxisValueRecord: - axisTag = designAxes[rec.AxisIndex].AxisTag - axisValue = rec.Value - if isAxisValueOutsideLimits(axisTag, axisValue): - dropAxisValueTable = True - break - if dropAxisValueTable: - continue - else: - log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat) - newAxisValueTables.append(axisValueTable) - return newAxisValueTables - - -def setMacOverlapFlags(glyfTable): - flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND - flagOverlapSimple = _g_l_y_f.flagOverlapSimple - for glyphName in glyfTable.keys(): - glyph = glyfTable[glyphName] - # Set OVERLAP_COMPOUND bit for compound glyphs - if glyph.isComposite(): - glyph.components[0].flags |= flagOverlapCompound - # Set OVERLAP_SIMPLE bit for simple glyphs - elif glyph.numberOfContours > 0: - glyph.flags[0] |= flagOverlapSimple - - -def normalize(value, triple, avarMapping): - value = normalizeValue(value, triple) - if avarMapping: - value = piecewiseLinearMap(value, avarMapping) - # Quantize to F2Dot14, to avoid surprise interpolations. - return floatToFixedToFloat(value, 14) - - -def sanityCheckVariableTables(varfont): - if "fvar" not in varfont: - raise ValueError("Missing required table fvar") - if "gvar" in varfont: - if "glyf" not in varfont: - raise ValueError("Can't have gvar without glyf") - # TODO(anthrotype) Remove once we do support partial instancing CFF2 - if "CFF2" in varfont: - raise NotImplementedError("Instancing CFF2 variable fonts is not supported yet") - - -def instantiateVariableFont( - varfont, - axisLimits, - inplace=False, - optimize=True, - overlap=OverlapMode.KEEP_AND_SET_FLAGS, - updateFontNames=False, -): - """Instantiate variable font, either fully or partially. - - Depending on whether the `axisLimits` dictionary references all or some of the - input varfont's axes, the output font will either be a full instance (static - font) or a variable font with possibly less variation data. - - Args: - varfont: a TTFont instance, which must contain at least an 'fvar' table. - Note that variable fonts with 'CFF2' table are not supported yet. - axisLimits: a dict keyed by axis tags (str) containing the coordinates (float) - along one or more axes where the desired instance will be located. - If the value is `None`, the default coordinate as per 'fvar' table for - that axis is used. - The limit values can also be (min, max) tuples for restricting an - axis's variation range. The default axis value must be included in - the new range. - inplace (bool): whether to modify input TTFont object in-place instead of - returning a distinct object. - optimize (bool): if False, do not perform IUP-delta optimization on the - remaining 'gvar' table's deltas. Possibly faster, and might work around - rendering issues in some buggy environments, at the cost of a slightly - larger file size. - overlap (OverlapMode): variable fonts usually contain overlapping contours, and - some font rendering engines on Apple platforms require that the - `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to - force rendering using a non-zero fill rule. Thus we always set these flags - on all glyphs to maximise cross-compatibility of the generated instance. - You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS. - If you want to remove the overlaps altogether and merge overlapping - contours and components, you can pass OverlapMode.REMOVE (or - REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this - requires the skia-pathops package (available to pip install). - The overlap parameter only has effect when generating full static instances. - updateFontNames (bool): if True, update the instantiated font's name table using - the Axis Value Tables from the STAT table. The name table and the style bits - in the head and OS/2 table will be updated so they conform to the R/I/B/BI - model. If the STAT table is missing or an Axis Value table is missing for - a given axis coordinate, a ValueError will be raised. - """ - # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool - overlap = OverlapMode(int(overlap)) - - sanityCheckVariableTables(varfont) - - axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont) - - log.info("Restricted limits: %s", axisLimits) - - normalizedLimits = axisLimits.normalize(varfont) - - log.info("Normalized limits: %s", normalizedLimits) - - if not inplace: - varfont = deepcopy(varfont) - - if "DSIG" in varfont: - del varfont["DSIG"] - - if updateFontNames: - log.info("Updating name table") - names.updateNameTable(varfont, axisLimits) - - if "gvar" in varfont: - instantiateGvar(varfont, normalizedLimits, optimize=optimize) - - if "cvar" in varfont: - instantiateCvar(varfont, normalizedLimits) - - if "MVAR" in varfont: - instantiateMVAR(varfont, normalizedLimits) - - if "HVAR" in varfont: - instantiateHVAR(varfont, normalizedLimits) - - if "VVAR" in varfont: - instantiateVVAR(varfont, normalizedLimits) - - instantiateOTL(varfont, normalizedLimits) - - instantiateFeatureVariations(varfont, normalizedLimits) - - if "avar" in varfont: - instantiateAvar(varfont, axisLimits) - - with names.pruningUnusedNames(varfont): - if "STAT" in varfont: - instantiateSTAT(varfont, axisLimits) - - instantiateFvar(varfont, axisLimits) - - if "fvar" not in varfont: - if "glyf" in varfont: - if overlap == OverlapMode.KEEP_AND_SET_FLAGS: - setMacOverlapFlags(varfont["glyf"]) - elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS): - from fontTools.ttLib.removeOverlaps import removeOverlaps - - log.info("Removing overlaps from glyf table") - removeOverlaps( - varfont, - ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS), - ) - - varLib.set_default_weight_width_slant( - varfont, location=axisLimits.defaultLocation() - ) - - if updateFontNames: - # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the - # name table has been updated. - setRibbiBits(varfont) - - return varfont - - -def setRibbiBits(font): - """Set the `head.macStyle` and `OS/2.fsSelection` style bits - appropriately.""" - - english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409) - if english_ribbi_style is None: - return - - styleMapStyleName = english_ribbi_style.toStr().lower() - if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}: - return - - if styleMapStyleName == "bold": - font["head"].macStyle = 0b01 - elif styleMapStyleName == "bold italic": - font["head"].macStyle = 0b11 - elif styleMapStyleName == "italic": - font["head"].macStyle = 0b10 - - selection = font["OS/2"].fsSelection - # First clear... - selection &= ~(1 << 0) - selection &= ~(1 << 5) - selection &= ~(1 << 6) - # ...then re-set the bits. - if styleMapStyleName == "regular": - selection |= 1 << 6 - elif styleMapStyleName == "bold": - selection |= 1 << 5 - elif styleMapStyleName == "italic": - selection |= 1 << 0 - elif styleMapStyleName == "bold italic": - selection |= 1 << 0 - selection |= 1 << 5 - font["OS/2"].fsSelection = selection - - -def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]: - result = {} - for limitString in limits: - match = re.match( - r"^(\w{1,4})=(?:(drop)|(?:([^:]+)(?:[:]([^:]+))?(?:[:]([^:]+))?))$", - limitString, - ) - if not match: - raise ValueError("invalid location format: %r" % limitString) - tag = match.group(1).ljust(4) - if match.group(2): # 'drop' - lbound = None - else: - lbound = strToFixedToFloat(match.group(3), precisionBits=16) - ubound = default = lbound - if match.group(4): - ubound = default = strToFixedToFloat(match.group(4), precisionBits=16) - default = None - if match.group(5): - default = ubound - ubound = strToFixedToFloat(match.group(5), precisionBits=16) - - if all(v is None for v in (lbound, default, ubound)): - result[tag] = None - continue - - result[tag] = AxisTriple(lbound, default, ubound) - - return result - - -def parseArgs(args): - """Parse argv. - - Returns: - 3-tuple (infile, axisLimits, options) - axisLimits is either a Dict[str, Optional[float]], for pinning variation axes - to specific coordinates along those axes (with `None` as a placeholder for an - axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this - axis to min/max range. - Axes locations are in user-space coordinates, as defined in the "fvar" table. - """ - from fontTools import configLogger - import argparse - - parser = argparse.ArgumentParser( - "fonttools varLib.instancer", - description="Partially instantiate a variable font", - ) - parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.") - parser.add_argument( - "locargs", - metavar="AXIS=LOC", - nargs="*", - help="List of space separated locations. A location consists of " - "the tag of a variation axis, followed by '=' and one of number, " - "number:number or the literal string 'drop'. " - "E.g.: wdth=100 or wght=75.0:125.0 or wght=drop", - ) - parser.add_argument( - "-o", - "--output", - metavar="OUTPUT.ttf", - default=None, - help="Output instance TTF file (default: INPUT-instance.ttf).", - ) - parser.add_argument( - "--no-optimize", - dest="optimize", - action="store_false", - help="Don't perform IUP optimization on the remaining gvar TupleVariations", - ) - parser.add_argument( - "--no-overlap-flag", - dest="overlap", - action="store_false", - help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable " - "when generating a full instance)", - ) - parser.add_argument( - "--remove-overlaps", - dest="remove_overlaps", - action="store_true", - help="Merge overlapping contours and components (only applicable " - "when generating a full instance). Requires skia-pathops", - ) - parser.add_argument( - "--ignore-overlap-errors", - dest="ignore_overlap_errors", - action="store_true", - help="Don't crash if the remove-overlaps operation fails for some glyphs.", - ) - parser.add_argument( - "--update-name-table", - action="store_true", - help="Update the instantiated font's `name` table. Input font must have " - "a STAT table with Axis Value Tables", - ) - parser.add_argument( - "--no-recalc-timestamp", - dest="recalc_timestamp", - action="store_false", - help="Don't set the output font's timestamp to the current time.", - ) - parser.add_argument( - "--no-recalc-bounds", - dest="recalc_bounds", - action="store_false", - help="Don't recalculate font bounding boxes", - ) - loggingGroup = parser.add_mutually_exclusive_group(required=False) - loggingGroup.add_argument( - "-v", "--verbose", action="store_true", help="Run more verbosely." - ) - loggingGroup.add_argument( - "-q", "--quiet", action="store_true", help="Turn verbosity off." - ) - options = parser.parse_args(args) - - if options.remove_overlaps: - if options.ignore_overlap_errors: - options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS - else: - options.overlap = OverlapMode.REMOVE - else: - options.overlap = OverlapMode(int(options.overlap)) - - infile = options.input - if not os.path.isfile(infile): - parser.error("No such file '{}'".format(infile)) - - configLogger( - level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") - ) - - try: - axisLimits = parseLimits(options.locargs) - except ValueError as e: - parser.error(str(e)) - - if len(axisLimits) != len(options.locargs): - parser.error("Specified multiple limits for the same axis") - - return (infile, axisLimits, options) - - -def main(args=None): - """Partially instantiate a variable font""" - infile, axisLimits, options = parseArgs(args) - log.info("Restricting axes: %s", axisLimits) - - log.info("Loading variable font") - varfont = TTFont( - infile, - recalcTimestamp=options.recalc_timestamp, - recalcBBoxes=options.recalc_bounds, - ) - - isFullInstance = { - axisTag for axisTag, limit in axisLimits.items() if not isinstance(limit, tuple) - }.issuperset(axis.axisTag for axis in varfont["fvar"].axes) - - instantiateVariableFont( - varfont, - axisLimits, - inplace=True, - optimize=options.optimize, - overlap=options.overlap, - updateFontNames=options.update_name_table, - ) - - suffix = "-instance" if isFullInstance else "-partial" - outfile = ( - makeOutputFileName(infile, overWrite=True, suffix=suffix) - if not options.output - else options.output - ) - - log.info( - "Saving %s font %s", - "instance" if isFullInstance else "partial variable", - outfile, - ) - varfont.save(outfile) diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/markdown_it/utils.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/markdown_it/utils.py deleted file mode 100644 index a97937208a73bf06817d523d03ba868ceb13a65a..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/markdown_it/utils.py +++ /dev/null @@ -1,176 +0,0 @@ -from __future__ import annotations - -from collections.abc import MutableMapping as MutableMappingABC -from pathlib import Path -from typing import Any, Callable, Iterable, MutableMapping, TypedDict, cast - -EnvType = MutableMapping[str, Any] # note: could use TypeAlias in python 3.10 -"""Type for the environment sandbox used in parsing and rendering, -which stores mutable variables for use by plugins and rules. -""" - - -class OptionsType(TypedDict): - """Options for parsing.""" - - maxNesting: int - """Internal protection, recursion limit.""" - html: bool - """Enable HTML tags in source.""" - linkify: bool - """Enable autoconversion of URL-like texts to links.""" - typographer: bool - """Enable smartquotes and replacements.""" - quotes: str - """Quote characters.""" - xhtmlOut: bool - """Use '/' to close single tags (
    ).""" - breaks: bool - """Convert newlines in paragraphs into
    .""" - langPrefix: str - """CSS language prefix for fenced blocks.""" - highlight: Callable[[str, str, str], str] | None - """Highlighter function: (content, lang, attrs) -> str.""" - - -class PresetType(TypedDict): - """Preset configuration for markdown-it.""" - - options: OptionsType - """Options for parsing.""" - components: MutableMapping[str, MutableMapping[str, list[str]]] - """Components for parsing and rendering.""" - - -class OptionsDict(MutableMappingABC): # type: ignore - """A dictionary, with attribute access to core markdownit configuration options.""" - - # Note: ideally we would probably just remove attribute access entirely, - # but we keep it for backwards compatibility. - - def __init__(self, options: OptionsType) -> None: - self._options = cast(OptionsType, dict(options)) - - def __getitem__(self, key: str) -> Any: - return self._options[key] # type: ignore[literal-required] - - def __setitem__(self, key: str, value: Any) -> None: - self._options[key] = value # type: ignore[literal-required] - - def __delitem__(self, key: str) -> None: - del self._options[key] # type: ignore - - def __iter__(self) -> Iterable[str]: # type: ignore - return iter(self._options) - - def __len__(self) -> int: - return len(self._options) - - def __repr__(self) -> str: - return repr(self._options) - - def __str__(self) -> str: - return str(self._options) - - @property - def maxNesting(self) -> int: - """Internal protection, recursion limit.""" - return self._options["maxNesting"] - - @maxNesting.setter - def maxNesting(self, value: int) -> None: - self._options["maxNesting"] = value - - @property - def html(self) -> bool: - """Enable HTML tags in source.""" - return self._options["html"] - - @html.setter - def html(self, value: bool) -> None: - self._options["html"] = value - - @property - def linkify(self) -> bool: - """Enable autoconversion of URL-like texts to links.""" - return self._options["linkify"] - - @linkify.setter - def linkify(self, value: bool) -> None: - self._options["linkify"] = value - - @property - def typographer(self) -> bool: - """Enable smartquotes and replacements.""" - return self._options["typographer"] - - @typographer.setter - def typographer(self, value: bool) -> None: - self._options["typographer"] = value - - @property - def quotes(self) -> str: - """Quote characters.""" - return self._options["quotes"] - - @quotes.setter - def quotes(self, value: str) -> None: - self._options["quotes"] = value - - @property - def xhtmlOut(self) -> bool: - """Use '/' to close single tags (
    ).""" - return self._options["xhtmlOut"] - - @xhtmlOut.setter - def xhtmlOut(self, value: bool) -> None: - self._options["xhtmlOut"] = value - - @property - def breaks(self) -> bool: - """Convert newlines in paragraphs into
    .""" - return self._options["breaks"] - - @breaks.setter - def breaks(self, value: bool) -> None: - self._options["breaks"] = value - - @property - def langPrefix(self) -> str: - """CSS language prefix for fenced blocks.""" - return self._options["langPrefix"] - - @langPrefix.setter - def langPrefix(self, value: str) -> None: - self._options["langPrefix"] = value - - @property - def highlight(self) -> Callable[[str, str, str], str] | None: - """Highlighter function: (content, langName, langAttrs) -> escaped HTML.""" - return self._options["highlight"] - - @highlight.setter - def highlight(self, value: Callable[[str, str, str], str] | None) -> None: - self._options["highlight"] = value - - -def read_fixture_file(path: str | Path) -> list[list[Any]]: - text = Path(path).read_text(encoding="utf-8") - tests = [] - section = 0 - last_pos = 0 - lines = text.splitlines(keepends=True) - for i in range(len(lines)): - if lines[i].rstrip() == ".": - if section == 0: - tests.append([i, lines[i - 1].strip()]) - section = 1 - elif section == 1: - tests[-1].append("".join(lines[last_pos + 1 : i])) - section = 2 - elif section == 2: - tests[-1].append("".join(lines[last_pos + 1 : i])) - section = 0 - - last_pos = i - return tests diff --git a/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/variational_autoencoder/modules.py b/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/variational_autoencoder/modules.py deleted file mode 100644 index 6b2c3dca2d168fb5fbaff5acc4b5a06280a496a7..0000000000000000000000000000000000000000 --- a/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/variational_autoencoder/modules.py +++ /dev/null @@ -1,1064 +0,0 @@ -# pytorch_diffusion + derived encoder decoder -import math -import torch -import torch.nn as nn -import numpy as np -from einops import rearrange - -from audioldm.utils import instantiate_from_config -from audioldm.latent_diffusion.attention import LinearAttention - -def get_timestep_embedding(timesteps, embedding_dim): - """ - This matches the implementation in Denoising Diffusion Probabilistic Models: - From Fairseq. - Build sinusoidal embeddings. - This matches the implementation in tensor2tensor, but differs slightly - from the description in Section 3.5 of "Attention Is All You Need". - """ - assert len(timesteps.shape) == 1 - - half_dim = embedding_dim // 2 - emb = math.log(10000) / (half_dim - 1) - emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) - emb = emb.to(device=timesteps.device) - emb = timesteps.float()[:, None] * emb[None, :] - emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) - if embedding_dim % 2 == 1: # zero pad - emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) - return emb - -def nonlinearity(x): - # swish - return x * torch.sigmoid(x) - - -def Normalize(in_channels, num_groups=32): - return torch.nn.GroupNorm( - num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True - ) - - -class Upsample(nn.Module): - def __init__(self, in_channels, with_conv): - super().__init__() - self.with_conv = with_conv - if self.with_conv: - self.conv = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=3, stride=1, padding=1 - ) - - def forward(self, x): - x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") - if self.with_conv: - x = self.conv(x) - return x - - -class UpsampleTimeStride4(nn.Module): - def __init__(self, in_channels, with_conv): - super().__init__() - self.with_conv = with_conv - if self.with_conv: - self.conv = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=5, stride=1, padding=2 - ) - - def forward(self, x): - x = torch.nn.functional.interpolate(x, scale_factor=(4.0, 2.0), mode="nearest") - if self.with_conv: - x = self.conv(x) - return x - - -class Downsample(nn.Module): - def __init__(self, in_channels, with_conv): - super().__init__() - self.with_conv = with_conv - if self.with_conv: - # Do time downsampling here - # no asymmetric padding in torch conv, must do it ourselves - self.conv = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=3, stride=2, padding=0 - ) - - def forward(self, x): - if self.with_conv: - pad = (0, 1, 0, 1) - x = torch.nn.functional.pad(x, pad, mode="constant", value=0) - x = self.conv(x) - else: - x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) - return x - - -class DownsampleTimeStride4(nn.Module): - def __init__(self, in_channels, with_conv): - super().__init__() - self.with_conv = with_conv - if self.with_conv: - # Do time downsampling here - # no asymmetric padding in torch conv, must do it ourselves - self.conv = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=5, stride=(4, 2), padding=1 - ) - - def forward(self, x): - if self.with_conv: - pad = (0, 1, 0, 1) - x = torch.nn.functional.pad(x, pad, mode="constant", value=0) - x = self.conv(x) - else: - x = torch.nn.functional.avg_pool2d(x, kernel_size=(4, 2), stride=(4, 2)) - return x - - -class ResnetBlock(nn.Module): - def __init__( - self, - *, - in_channels, - out_channels=None, - conv_shortcut=False, - dropout, - temb_channels=512, - ): - super().__init__() - self.in_channels = in_channels - out_channels = in_channels if out_channels is None else out_channels - self.out_channels = out_channels - self.use_conv_shortcut = conv_shortcut - - self.norm1 = Normalize(in_channels) - self.conv1 = torch.nn.Conv2d( - in_channels, out_channels, kernel_size=3, stride=1, padding=1 - ) - if temb_channels > 0: - self.temb_proj = torch.nn.Linear(temb_channels, out_channels) - self.norm2 = Normalize(out_channels) - self.dropout = torch.nn.Dropout(dropout) - self.conv2 = torch.nn.Conv2d( - out_channels, out_channels, kernel_size=3, stride=1, padding=1 - ) - if self.in_channels != self.out_channels: - if self.use_conv_shortcut: - self.conv_shortcut = torch.nn.Conv2d( - in_channels, out_channels, kernel_size=3, stride=1, padding=1 - ) - else: - self.nin_shortcut = torch.nn.Conv2d( - in_channels, out_channels, kernel_size=1, stride=1, padding=0 - ) - - def forward(self, x, temb): - h = x - h = self.norm1(h) - h = nonlinearity(h) - h = self.conv1(h) - - if temb is not None: - h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None] - - h = self.norm2(h) - h = nonlinearity(h) - h = self.dropout(h) - h = self.conv2(h) - - if self.in_channels != self.out_channels: - if self.use_conv_shortcut: - x = self.conv_shortcut(x) - else: - x = self.nin_shortcut(x) - - return x + h - - -class LinAttnBlock(LinearAttention): - """to match AttnBlock usage""" - - def __init__(self, in_channels): - super().__init__(dim=in_channels, heads=1, dim_head=in_channels) - - -class AttnBlock(nn.Module): - def __init__(self, in_channels): - super().__init__() - self.in_channels = in_channels - - self.norm = Normalize(in_channels) - self.q = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=1, stride=1, padding=0 - ) - self.k = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=1, stride=1, padding=0 - ) - self.v = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=1, stride=1, padding=0 - ) - self.proj_out = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=1, stride=1, padding=0 - ) - - def forward(self, x): - h_ = x - h_ = self.norm(h_) - q = self.q(h_) - k = self.k(h_) - v = self.v(h_) - - # compute attention - b, c, h, w = q.shape - q = q.reshape(b, c, h * w).contiguous() - q = q.permute(0, 2, 1).contiguous() # b,hw,c - k = k.reshape(b, c, h * w).contiguous() # b,c,hw - w_ = torch.bmm(q, k).contiguous() # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] - w_ = w_ * (int(c) ** (-0.5)) - w_ = torch.nn.functional.softmax(w_, dim=2) - - # attend to values - v = v.reshape(b, c, h * w).contiguous() - w_ = w_.permute(0, 2, 1).contiguous() # b,hw,hw (first hw of k, second of q) - h_ = torch.bmm( - v, w_ - ).contiguous() # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] - h_ = h_.reshape(b, c, h, w).contiguous() - - h_ = self.proj_out(h_) - - return x + h_ - - -def make_attn(in_channels, attn_type="vanilla"): - assert attn_type in ["vanilla", "linear", "none"], f"attn_type {attn_type} unknown" - # print(f"making attention of type '{attn_type}' with {in_channels} in_channels") - if attn_type == "vanilla": - return AttnBlock(in_channels) - elif attn_type == "none": - return nn.Identity(in_channels) - else: - return LinAttnBlock(in_channels) - - -class Model(nn.Module): - def __init__( - self, - *, - ch, - out_ch, - ch_mult=(1, 2, 4, 8), - num_res_blocks, - attn_resolutions, - dropout=0.0, - resamp_with_conv=True, - in_channels, - resolution, - use_timestep=True, - use_linear_attn=False, - attn_type="vanilla", - ): - super().__init__() - if use_linear_attn: - attn_type = "linear" - self.ch = ch - self.temb_ch = self.ch * 4 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - self.resolution = resolution - self.in_channels = in_channels - - self.use_timestep = use_timestep - if self.use_timestep: - # timestep embedding - self.temb = nn.Module() - self.temb.dense = nn.ModuleList( - [ - torch.nn.Linear(self.ch, self.temb_ch), - torch.nn.Linear(self.temb_ch, self.temb_ch), - ] - ) - - # downsampling - self.conv_in = torch.nn.Conv2d( - in_channels, self.ch, kernel_size=3, stride=1, padding=1 - ) - - curr_res = resolution - in_ch_mult = (1,) + tuple(ch_mult) - self.down = nn.ModuleList() - for i_level in range(self.num_resolutions): - block = nn.ModuleList() - attn = nn.ModuleList() - block_in = ch * in_ch_mult[i_level] - block_out = ch * ch_mult[i_level] - for i_block in range(self.num_res_blocks): - block.append( - ResnetBlock( - in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout, - ) - ) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - down = nn.Module() - down.block = block - down.attn = attn - if i_level != self.num_resolutions - 1: - down.downsample = Downsample(block_in, resamp_with_conv) - curr_res = curr_res // 2 - self.down.append(down) - - # middle - self.mid = nn.Module() - self.mid.block_1 = ResnetBlock( - in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout, - ) - self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) - self.mid.block_2 = ResnetBlock( - in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout, - ) - - # upsampling - self.up = nn.ModuleList() - for i_level in reversed(range(self.num_resolutions)): - block = nn.ModuleList() - attn = nn.ModuleList() - block_out = ch * ch_mult[i_level] - skip_in = ch * ch_mult[i_level] - for i_block in range(self.num_res_blocks + 1): - if i_block == self.num_res_blocks: - skip_in = ch * in_ch_mult[i_level] - block.append( - ResnetBlock( - in_channels=block_in + skip_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout, - ) - ) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - up = nn.Module() - up.block = block - up.attn = attn - if i_level != 0: - up.upsample = Upsample(block_in, resamp_with_conv) - curr_res = curr_res * 2 - self.up.insert(0, up) # prepend to get consistent order - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d( - block_in, out_ch, kernel_size=3, stride=1, padding=1 - ) - - def forward(self, x, t=None, context=None): - # assert x.shape[2] == x.shape[3] == self.resolution - if context is not None: - # assume aligned context, cat along channel axis - x = torch.cat((x, context), dim=1) - if self.use_timestep: - # timestep embedding - assert t is not None - temb = get_timestep_embedding(t, self.ch) - temb = self.temb.dense[0](temb) - temb = nonlinearity(temb) - temb = self.temb.dense[1](temb) - else: - temb = None - - # downsampling - hs = [self.conv_in(x)] - for i_level in range(self.num_resolutions): - for i_block in range(self.num_res_blocks): - h = self.down[i_level].block[i_block](hs[-1], temb) - if len(self.down[i_level].attn) > 0: - h = self.down[i_level].attn[i_block](h) - hs.append(h) - if i_level != self.num_resolutions - 1: - hs.append(self.down[i_level].downsample(hs[-1])) - - # middle - h = hs[-1] - h = self.mid.block_1(h, temb) - h = self.mid.attn_1(h) - h = self.mid.block_2(h, temb) - - # upsampling - for i_level in reversed(range(self.num_resolutions)): - for i_block in range(self.num_res_blocks + 1): - h = self.up[i_level].block[i_block]( - torch.cat([h, hs.pop()], dim=1), temb - ) - if len(self.up[i_level].attn) > 0: - h = self.up[i_level].attn[i_block](h) - if i_level != 0: - h = self.up[i_level].upsample(h) - - # end - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - return h - - def get_last_layer(self): - return self.conv_out.weight - - -class Encoder(nn.Module): - def __init__( - self, - *, - ch, - out_ch, - ch_mult=(1, 2, 4, 8), - num_res_blocks, - attn_resolutions, - dropout=0.0, - resamp_with_conv=True, - in_channels, - resolution, - z_channels, - double_z=True, - use_linear_attn=False, - attn_type="vanilla", - downsample_time_stride4_levels=[], - **ignore_kwargs, - ): - super().__init__() - if use_linear_attn: - attn_type = "linear" - self.ch = ch - self.temb_ch = 0 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - self.resolution = resolution - self.in_channels = in_channels - self.downsample_time_stride4_levels = downsample_time_stride4_levels - - if len(self.downsample_time_stride4_levels) > 0: - assert max(self.downsample_time_stride4_levels) < self.num_resolutions, ( - "The level to perform downsample 4 operation need to be smaller than the total resolution number %s" - % str(self.num_resolutions) - ) - - # downsampling - self.conv_in = torch.nn.Conv2d( - in_channels, self.ch, kernel_size=3, stride=1, padding=1 - ) - - curr_res = resolution - in_ch_mult = (1,) + tuple(ch_mult) - self.in_ch_mult = in_ch_mult - self.down = nn.ModuleList() - for i_level in range(self.num_resolutions): - block = nn.ModuleList() - attn = nn.ModuleList() - block_in = ch * in_ch_mult[i_level] - block_out = ch * ch_mult[i_level] - for i_block in range(self.num_res_blocks): - block.append( - ResnetBlock( - in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout, - ) - ) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - down = nn.Module() - down.block = block - down.attn = attn - if i_level != self.num_resolutions - 1: - if i_level in self.downsample_time_stride4_levels: - down.downsample = DownsampleTimeStride4(block_in, resamp_with_conv) - else: - down.downsample = Downsample(block_in, resamp_with_conv) - curr_res = curr_res // 2 - self.down.append(down) - - # middle - self.mid = nn.Module() - self.mid.block_1 = ResnetBlock( - in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout, - ) - self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) - self.mid.block_2 = ResnetBlock( - in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout, - ) - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d( - block_in, - 2 * z_channels if double_z else z_channels, - kernel_size=3, - stride=1, - padding=1, - ) - - def forward(self, x): - # timestep embedding - temb = None - # downsampling - hs = [self.conv_in(x)] - for i_level in range(self.num_resolutions): - for i_block in range(self.num_res_blocks): - h = self.down[i_level].block[i_block](hs[-1], temb) - if len(self.down[i_level].attn) > 0: - h = self.down[i_level].attn[i_block](h) - hs.append(h) - if i_level != self.num_resolutions - 1: - hs.append(self.down[i_level].downsample(hs[-1])) - - # middle - h = hs[-1] - h = self.mid.block_1(h, temb) - h = self.mid.attn_1(h) - h = self.mid.block_2(h, temb) - - # end - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - return h - - -class Decoder(nn.Module): - def __init__( - self, - *, - ch, - out_ch, - ch_mult=(1, 2, 4, 8), - num_res_blocks, - attn_resolutions, - dropout=0.0, - resamp_with_conv=True, - in_channels, - resolution, - z_channels, - give_pre_end=False, - tanh_out=False, - use_linear_attn=False, - downsample_time_stride4_levels=[], - attn_type="vanilla", - **ignorekwargs, - ): - super().__init__() - if use_linear_attn: - attn_type = "linear" - self.ch = ch - self.temb_ch = 0 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - self.resolution = resolution - self.in_channels = in_channels - self.give_pre_end = give_pre_end - self.tanh_out = tanh_out - self.downsample_time_stride4_levels = downsample_time_stride4_levels - - if len(self.downsample_time_stride4_levels) > 0: - assert max(self.downsample_time_stride4_levels) < self.num_resolutions, ( - "The level to perform downsample 4 operation need to be smaller than the total resolution number %s" - % str(self.num_resolutions) - ) - - # compute in_ch_mult, block_in and curr_res at lowest res - in_ch_mult = (1,) + tuple(ch_mult) - block_in = ch * ch_mult[self.num_resolutions - 1] - curr_res = resolution // 2 ** (self.num_resolutions - 1) - self.z_shape = (1, z_channels, curr_res, curr_res) - # print("Working with z of shape {} = {} dimensions.".format( - # self.z_shape, np.prod(self.z_shape))) - - # z to block_in - self.conv_in = torch.nn.Conv2d( - z_channels, block_in, kernel_size=3, stride=1, padding=1 - ) - - # middle - self.mid = nn.Module() - self.mid.block_1 = ResnetBlock( - in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout, - ) - self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) - self.mid.block_2 = ResnetBlock( - in_channels=block_in, - out_channels=block_in, - temb_channels=self.temb_ch, - dropout=dropout, - ) - - # upsampling - self.up = nn.ModuleList() - for i_level in reversed(range(self.num_resolutions)): - block = nn.ModuleList() - attn = nn.ModuleList() - block_out = ch * ch_mult[i_level] - for i_block in range(self.num_res_blocks + 1): - block.append( - ResnetBlock( - in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout, - ) - ) - block_in = block_out - if curr_res in attn_resolutions: - attn.append(make_attn(block_in, attn_type=attn_type)) - up = nn.Module() - up.block = block - up.attn = attn - if i_level != 0: - if i_level - 1 in self.downsample_time_stride4_levels: - up.upsample = UpsampleTimeStride4(block_in, resamp_with_conv) - else: - up.upsample = Upsample(block_in, resamp_with_conv) - curr_res = curr_res * 2 - self.up.insert(0, up) # prepend to get consistent order - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d( - block_in, out_ch, kernel_size=3, stride=1, padding=1 - ) - - def forward(self, z): - # assert z.shape[1:] == self.z_shape[1:] - self.last_z_shape = z.shape - - # timestep embedding - temb = None - - # z to block_in - h = self.conv_in(z) - - # middle - h = self.mid.block_1(h, temb) - h = self.mid.attn_1(h) - h = self.mid.block_2(h, temb) - - # upsampling - for i_level in reversed(range(self.num_resolutions)): - for i_block in range(self.num_res_blocks + 1): - h = self.up[i_level].block[i_block](h, temb) - if len(self.up[i_level].attn) > 0: - h = self.up[i_level].attn[i_block](h) - if i_level != 0: - h = self.up[i_level].upsample(h) - - # end - if self.give_pre_end: - return h - - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - if self.tanh_out: - h = torch.tanh(h) - return h - - -class SimpleDecoder(nn.Module): - def __init__(self, in_channels, out_channels, *args, **kwargs): - super().__init__() - self.model = nn.ModuleList( - [ - nn.Conv2d(in_channels, in_channels, 1), - ResnetBlock( - in_channels=in_channels, - out_channels=2 * in_channels, - temb_channels=0, - dropout=0.0, - ), - ResnetBlock( - in_channels=2 * in_channels, - out_channels=4 * in_channels, - temb_channels=0, - dropout=0.0, - ), - ResnetBlock( - in_channels=4 * in_channels, - out_channels=2 * in_channels, - temb_channels=0, - dropout=0.0, - ), - nn.Conv2d(2 * in_channels, in_channels, 1), - Upsample(in_channels, with_conv=True), - ] - ) - # end - self.norm_out = Normalize(in_channels) - self.conv_out = torch.nn.Conv2d( - in_channels, out_channels, kernel_size=3, stride=1, padding=1 - ) - - def forward(self, x): - for i, layer in enumerate(self.model): - if i in [1, 2, 3]: - x = layer(x, None) - else: - x = layer(x) - - h = self.norm_out(x) - h = nonlinearity(h) - x = self.conv_out(h) - return x - - -class UpsampleDecoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - ch, - num_res_blocks, - resolution, - ch_mult=(2, 2), - dropout=0.0, - ): - super().__init__() - # upsampling - self.temb_ch = 0 - self.num_resolutions = len(ch_mult) - self.num_res_blocks = num_res_blocks - block_in = in_channels - curr_res = resolution // 2 ** (self.num_resolutions - 1) - self.res_blocks = nn.ModuleList() - self.upsample_blocks = nn.ModuleList() - for i_level in range(self.num_resolutions): - res_block = [] - block_out = ch * ch_mult[i_level] - for i_block in range(self.num_res_blocks + 1): - res_block.append( - ResnetBlock( - in_channels=block_in, - out_channels=block_out, - temb_channels=self.temb_ch, - dropout=dropout, - ) - ) - block_in = block_out - self.res_blocks.append(nn.ModuleList(res_block)) - if i_level != self.num_resolutions - 1: - self.upsample_blocks.append(Upsample(block_in, True)) - curr_res = curr_res * 2 - - # end - self.norm_out = Normalize(block_in) - self.conv_out = torch.nn.Conv2d( - block_in, out_channels, kernel_size=3, stride=1, padding=1 - ) - - def forward(self, x): - # upsampling - h = x - for k, i_level in enumerate(range(self.num_resolutions)): - for i_block in range(self.num_res_blocks + 1): - h = self.res_blocks[i_level][i_block](h, None) - if i_level != self.num_resolutions - 1: - h = self.upsample_blocks[k](h) - h = self.norm_out(h) - h = nonlinearity(h) - h = self.conv_out(h) - return h - - -class LatentRescaler(nn.Module): - def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2): - super().__init__() - # residual block, interpolate, residual block - self.factor = factor - self.conv_in = nn.Conv2d( - in_channels, mid_channels, kernel_size=3, stride=1, padding=1 - ) - self.res_block1 = nn.ModuleList( - [ - ResnetBlock( - in_channels=mid_channels, - out_channels=mid_channels, - temb_channels=0, - dropout=0.0, - ) - for _ in range(depth) - ] - ) - self.attn = AttnBlock(mid_channels) - self.res_block2 = nn.ModuleList( - [ - ResnetBlock( - in_channels=mid_channels, - out_channels=mid_channels, - temb_channels=0, - dropout=0.0, - ) - for _ in range(depth) - ] - ) - - self.conv_out = nn.Conv2d( - mid_channels, - out_channels, - kernel_size=1, - ) - - def forward(self, x): - x = self.conv_in(x) - for block in self.res_block1: - x = block(x, None) - x = torch.nn.functional.interpolate( - x, - size=( - int(round(x.shape[2] * self.factor)), - int(round(x.shape[3] * self.factor)), - ), - ) - x = self.attn(x).contiguous() - for block in self.res_block2: - x = block(x, None) - x = self.conv_out(x) - return x - - -class MergedRescaleEncoder(nn.Module): - def __init__( - self, - in_channels, - ch, - resolution, - out_ch, - num_res_blocks, - attn_resolutions, - dropout=0.0, - resamp_with_conv=True, - ch_mult=(1, 2, 4, 8), - rescale_factor=1.0, - rescale_module_depth=1, - ): - super().__init__() - intermediate_chn = ch * ch_mult[-1] - self.encoder = Encoder( - in_channels=in_channels, - num_res_blocks=num_res_blocks, - ch=ch, - ch_mult=ch_mult, - z_channels=intermediate_chn, - double_z=False, - resolution=resolution, - attn_resolutions=attn_resolutions, - dropout=dropout, - resamp_with_conv=resamp_with_conv, - out_ch=None, - ) - self.rescaler = LatentRescaler( - factor=rescale_factor, - in_channels=intermediate_chn, - mid_channels=intermediate_chn, - out_channels=out_ch, - depth=rescale_module_depth, - ) - - def forward(self, x): - x = self.encoder(x) - x = self.rescaler(x) - return x - - -class MergedRescaleDecoder(nn.Module): - def __init__( - self, - z_channels, - out_ch, - resolution, - num_res_blocks, - attn_resolutions, - ch, - ch_mult=(1, 2, 4, 8), - dropout=0.0, - resamp_with_conv=True, - rescale_factor=1.0, - rescale_module_depth=1, - ): - super().__init__() - tmp_chn = z_channels * ch_mult[-1] - self.decoder = Decoder( - out_ch=out_ch, - z_channels=tmp_chn, - attn_resolutions=attn_resolutions, - dropout=dropout, - resamp_with_conv=resamp_with_conv, - in_channels=None, - num_res_blocks=num_res_blocks, - ch_mult=ch_mult, - resolution=resolution, - ch=ch, - ) - self.rescaler = LatentRescaler( - factor=rescale_factor, - in_channels=z_channels, - mid_channels=tmp_chn, - out_channels=tmp_chn, - depth=rescale_module_depth, - ) - - def forward(self, x): - x = self.rescaler(x) - x = self.decoder(x) - return x - - -class Upsampler(nn.Module): - def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2): - super().__init__() - assert out_size >= in_size - num_blocks = int(np.log2(out_size // in_size)) + 1 - factor_up = 1.0 + (out_size % in_size) - print( - f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}" - ) - self.rescaler = LatentRescaler( - factor=factor_up, - in_channels=in_channels, - mid_channels=2 * in_channels, - out_channels=in_channels, - ) - self.decoder = Decoder( - out_ch=out_channels, - resolution=out_size, - z_channels=in_channels, - num_res_blocks=2, - attn_resolutions=[], - in_channels=None, - ch=in_channels, - ch_mult=[ch_mult for _ in range(num_blocks)], - ) - - def forward(self, x): - x = self.rescaler(x) - x = self.decoder(x) - return x - - -class Resize(nn.Module): - def __init__(self, in_channels=None, learned=False, mode="bilinear"): - super().__init__() - self.with_conv = learned - self.mode = mode - if self.with_conv: - print( - f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode" - ) - raise NotImplementedError() - assert in_channels is not None - # no asymmetric padding in torch conv, must do it ourselves - self.conv = torch.nn.Conv2d( - in_channels, in_channels, kernel_size=4, stride=2, padding=1 - ) - - def forward(self, x, scale_factor=1.0): - if scale_factor == 1.0: - return x - else: - x = torch.nn.functional.interpolate( - x, mode=self.mode, align_corners=False, scale_factor=scale_factor - ) - return x - - -class FirstStagePostProcessor(nn.Module): - def __init__( - self, - ch_mult: list, - in_channels, - pretrained_model: nn.Module = None, - reshape=False, - n_channels=None, - dropout=0.0, - pretrained_config=None, - ): - super().__init__() - if pretrained_config is None: - assert ( - pretrained_model is not None - ), 'Either "pretrained_model" or "pretrained_config" must not be None' - self.pretrained_model = pretrained_model - else: - assert ( - pretrained_config is not None - ), 'Either "pretrained_model" or "pretrained_config" must not be None' - self.instantiate_pretrained(pretrained_config) - - self.do_reshape = reshape - - if n_channels is None: - n_channels = self.pretrained_model.encoder.ch - - self.proj_norm = Normalize(in_channels, num_groups=in_channels // 2) - self.proj = nn.Conv2d( - in_channels, n_channels, kernel_size=3, stride=1, padding=1 - ) - - blocks = [] - downs = [] - ch_in = n_channels - for m in ch_mult: - blocks.append( - ResnetBlock( - in_channels=ch_in, out_channels=m * n_channels, dropout=dropout - ) - ) - ch_in = m * n_channels - downs.append(Downsample(ch_in, with_conv=False)) - - self.model = nn.ModuleList(blocks) - self.downsampler = nn.ModuleList(downs) - - def instantiate_pretrained(self, config): - model = instantiate_from_config(config) - self.pretrained_model = model.eval() - # self.pretrained_model.train = False - for param in self.pretrained_model.parameters(): - param.requires_grad = False - - @torch.no_grad() - def encode_with_pretrained(self, x): - c = self.pretrained_model.encode(x) - if isinstance(c, DiagonalGaussianDistribution): - c = c.mode() - return c - - def forward(self, x): - z_fs = self.encode_with_pretrained(x) - z = self.proj_norm(z_fs) - z = self.proj(z) - z = nonlinearity(z) - - for submodel, downmodel in zip(self.model, self.downsampler): - z = submodel(z, temb=None) - z = downmodel(z) - - if self.do_reshape: - z = rearrange(z, "b c h w -> b (h w) c") - return z diff --git a/spaces/derful/Chatgpt-academic/crazy_functions/test_project/latex/attention/model_architecture.tex b/spaces/derful/Chatgpt-academic/crazy_functions/test_project/latex/attention/model_architecture.tex deleted file mode 100644 index c82be6242cc9d26203360e90d3ac9184ef6ad842..0000000000000000000000000000000000000000 --- a/spaces/derful/Chatgpt-academic/crazy_functions/test_project/latex/attention/model_architecture.tex +++ /dev/null @@ -1,155 +0,0 @@ - -\begin{figure} - \centering - \includegraphics[scale=0.6]{Figures/ModalNet-21} - \caption{The Transformer - model architecture.} - \label{fig:model-arch} -\end{figure} - -% Although the primary workhorse of our model is attention, -%Our model maintains the encoder-decoder structure that is common to many so-called sequence-to-sequence models \citep{bahdanau2014neural,sutskever14}. As in all such architectures, the encoder computes a representation of the input sequence, and the decoder consumes these representations along with the output tokens to autoregressively produce the output sequence. Where, traditionally, the encoder and decoder contain stacks of recurrent or convolutional layers, our encoder and decoder stacks are composed of attention layers and position-wise feed-forward layers (Figure~\ref{fig:model-arch}). The following sections describe the gross architecture and these particular components in detail. - -Most competitive neural sequence transduction models have an encoder-decoder structure \citep{cho2014learning,bahdanau2014neural,sutskever14}. Here, the encoder maps an input sequence of symbol representations $(x_1, ..., x_n)$ to a sequence of continuous representations $\mathbf{z} = (z_1, ..., z_n)$. Given $\mathbf{z}$, the decoder then generates an output sequence $(y_1,...,y_m)$ of symbols one element at a time. At each step the model is auto-regressive \citep{graves2013generating}, consuming the previously generated symbols as additional input when generating the next. - -The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure~\ref{fig:model-arch}, respectively. - -\subsection{Encoder and Decoder Stacks} - -\paragraph{Encoder:}The encoder is composed of a stack of $N=6$ identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-wise fully connected feed-forward network. We employ a residual connection \citep{he2016deep} around each of the two sub-layers, followed by layer normalization \cite{layernorm2016}. That is, the output of each sub-layer is $\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x))$, where $\mathrm{Sublayer}(x)$ is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension $\dmodel=512$. - -\paragraph{Decoder:}The decoder is also composed of a stack of $N=6$ identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$. - -% In our model (Figure~\ref{fig:model-arch}), the encoder and decoder are composed of stacks of alternating self-attention layers (for cross-positional communication) and position-wise feed-forward layers (for in-place computation). In addition, the decoder stack contains encoder-decoder attention layers. Since attention is agnostic to the distances between words, our model requires a "positional encoding" to be added to the encoder and decoder input. The following sections describe all of these components in detail. - -\subsection{Attention} \label{sec:attention} -An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key. - -\subsubsection{Scaled Dot-Product Attention} \label{sec:scaled-dot-prod} - -% \begin{figure} -% \centering -% \includegraphics[scale=0.6]{Figures/ModalNet-19} -% \caption{Scaled Dot-Product Attention.} -% \label{fig:multi-head-att} -% \end{figure} - -We call our particular attention "Scaled Dot-Product Attention" (Figure~\ref{fig:multi-head-att}). The input consists of queries and keys of dimension $d_k$, and values of dimension $d_v$. We compute the dot products of the query with all keys, divide each by $\sqrt{d_k}$, and apply a softmax function to obtain the weights on the values. - -In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix $Q$. The keys and values are also packed together into matrices $K$ and $V$. We compute the matrix of outputs as: - -\begin{equation} - \mathrm{Attention}(Q, K, V) = \mathrm{softmax}(\frac{QK^T}{\sqrt{d_k}})V -\end{equation} - -The two most commonly used attention functions are additive attention \citep{bahdanau2014neural}, and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of $\frac{1}{\sqrt{d_k}}$. Additive attention computes the compatibility function using a feed-forward network with a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code. - -%We scale the dot products by $1/\sqrt{d_k}$ to limit the magnitude of the dot products, which works well in practice. Otherwise, we found applying the softmax to often result in weights very close to 0 or 1, and hence minuscule gradients. - -% Already described in the subsequent section -%When used as part of decoder self-attention, an optional mask function is applied just before the softmax to prevent positions from attending to subsequent positions. This mask simply sets the logits corresponding to all illegal connections (those outside of the lower triangle) to $-\infty$. - -%\paragraph{Comparison to Additive Attention: } We choose dot product attention over additive attention \citep{bahdanau2014neural} since it can be computed using highly optimized matrix multiplication code. This optimization is particularly important to us, as we employ many attention layers in our model. - -While for small values of $d_k$ the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of $d_k$ \citep{DBLP:journals/corr/BritzGLL17}. We suspect that for large values of $d_k$, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients \footnote{To illustrate why the dot products get large, assume that the components of $q$ and $k$ are independent random variables with mean $0$ and variance $1$. Then their dot product, $q \cdot k = \sum_{i=1}^{d_k} q_ik_i$, has mean $0$ and variance $d_k$.}. To counteract this effect, we scale the dot products by $\frac{1}{\sqrt{d_k}}$. - - -%We suspect this to be caused by the dot products growing too large in magnitude to result in useful gradients after applying the softmax function. To counteract this, we scale the dot product by $1/\sqrt{d_k}$. - - -\subsubsection{Multi-Head Attention} \label{sec:multihead} - -\begin{figure} -\begin{minipage}[t]{0.5\textwidth} - \centering - Scaled Dot-Product Attention \\ - \vspace{0.5cm} - \includegraphics[scale=0.6]{Figures/ModalNet-19} -\end{minipage} -\begin{minipage}[t]{0.5\textwidth} - \centering - Multi-Head Attention \\ - \vspace{0.1cm} - \includegraphics[scale=0.6]{Figures/ModalNet-20} -\end{minipage} - - - % \centering - - \caption{(left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.} - \label{fig:multi-head-att} -\end{figure} - -Instead of performing a single attention function with $\dmodel$-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values $h$ times with different, learned linear projections to $d_k$, $d_k$ and $d_v$ dimensions, respectively. -On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding $d_v$-dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure~\ref{fig:multi-head-att}. - -Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this. - -\begin{align*} - \mathrm{MultiHead}(Q, K, V) &= \mathrm{Concat}(\mathrm{head_1}, ..., \mathrm{head_h})W^O\\ -% \mathrm{where} \mathrm{head_i} &= \mathrm{Attention}(QW_Q_i^{\dmodel \times d_q}, KW_K_i^{\dmodel \times d_k}, VW^V_i^{\dmodel \times d_v})\\ - \text{where}~\mathrm{head_i} &= \mathrm{Attention}(QW^Q_i, KW^K_i, VW^V_i)\\ -\end{align*} - -Where the projections are parameter matrices $W^Q_i \in \mathbb{R}^{\dmodel \times d_k}$, $W^K_i \in \mathbb{R}^{\dmodel \times d_k}$, $W^V_i \in \mathbb{R}^{\dmodel \times d_v}$ and $W^O \in \mathbb{R}^{hd_v \times \dmodel}$. - - -%find it better (and no more expensive) to have multiple parallel attention layers (each over the full set of positions) with proportionally lower-dimensional keys, values and queries. We call this "Multi-Head Attention" (Figure~\ref{fig:multi-head-att}). The keys, values, and queries for each of these parallel attention layers are computed by learned linear transformations of the inputs to the multi-head attention. We use different linear transformations across different parallel attention layers. The output of the parallel attention layers are concatenated, and then passed through a final learned linear transformation. - -In this work we employ $h=8$ parallel attention layers, or heads. For each of these we use $d_k=d_v=\dmodel/h=64$. -Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality. - -\subsubsection{Applications of Attention in our Model} - -The Transformer uses multi-head attention in three different ways: -\begin{itemize} - \item In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as \citep{wu2016google, bahdanau2014neural,JonasFaceNet2017}. - - \item The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder. - - \item Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to $-\infty$) all values in the input of the softmax which correspond to illegal connections. See Figure~\ref{fig:multi-head-att}. - -\end{itemize} - -\subsection{Position-wise Feed-Forward Networks}\label{sec:ffn} - -In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between. - -\begin{equation} - \mathrm{FFN}(x)=\max(0, xW_1 + b_1) W_2 + b_2 -\end{equation} - -While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is $\dmodel=512$, and the inner-layer has dimensionality $d_{ff}=2048$. - - - -%In the appendix, we describe how the position-wise feed-forward network can also be seen as a form of attention. - -%from Jakob: The number of operations required for the model to relate signals from two arbitrary input or output positions grows in the distance between positions in input or output, linearly for ConvS2S and logarithmically for ByteNet, making it harder to learn dependencies between these positions \citep{hochreiter2001gradient}. In the transformer this is reduced to a constant number of operations, albeit at the cost of effective resolution caused by averaging attention-weighted positions, an effect we aim to counteract with multi-headed attention. - - -%Figure~\ref{fig:simple-att} presents a simple attention function, $A$, with a single head, that forms the basis of our multi-head attention. $A$ takes a query key vector $\kq$, matrices of memory keys $\km$ and memory values $\vm$ ,and produces a query value vector $\vq$ as -%\begin{equation*} \label{eq:attention} -% A(\kq, \km, \vm) = {\vm}^T (Softmax(\km \kq). -%\end{equation*} -%We linearly transform $\kq,\,\km$, and $\vm$ with learned matrices ${\Wkq \text{,} \, \Wkm}$, and ${\Wvm}$ before calling the attention function, and transform the output query with $\Wvq$ before handing it to the feed forward layer. Each attention layer has it's own set of transformation matrices, which are shared across all query positions. $A$ is applied in parallel for each query position, and is implemented very efficiently as a batch of matrix multiplies. The self-attention and encoder-decoder attention layers use $A$, but with different arguments. For example, in encdoder self-attention, queries in encoder layer $i$ attention to memories in encoder layer $i-1$. To ensure that decoder self-attention layers do not look at future words, we add $- \inf$ to the softmax logits in positions $j+1$ to query length for query position $l$. - -%In simple attention, the query value is a weighted combination of the memory values where the attention weights sum to one. Although this function performs well in practice, the constraint on attention weights can restrict the amount of information that flows from memories to queries because the query cannot focus on multiple memory positions at once, which might be desirable when translating long sequences. \marginpar{@usz, could you think of an example of this ?} We remedy this by maintaining multiple attention heads at each query position that attend to all memory positions in parallel, with a different set of parameters per attention head $h$. -%\marginpar{} - -\subsection{Embeddings and Softmax} -Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension $\dmodel$. We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to \citep{press2016using}. In the embedding layers, we multiply those weights by $\sqrt{\dmodel}$. - - -\subsection{Positional Encoding} -Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension $\dmodel$ as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed \citep{JonasFaceNet2017}. - -In this work, we use sine and cosine functions of different frequencies: - -\begin{align*} - PE_{(pos,2i)} = sin(pos / 10000^{2i/\dmodel}) \\ - PE_{(pos,2i+1)} = cos(pos / 10000^{2i/\dmodel}) -\end{align*} - -where $pos$ is the position and $i$ is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from $2\pi$ to $10000 \cdot 2\pi$. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset $k$, $PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$. - -We also experimented with using learned positional embeddings \citep{JonasFaceNet2017} instead, and found that the two versions produced nearly identical results (see Table~\ref{tab:variations} row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training. diff --git a/spaces/diacanFperku/AutoGPT/AutoCAD 2018 [64bit] Pre Release Incl Keygen X FORCE [MUMBAI TPB].epub !!EXCLUSIVE!!.md b/spaces/diacanFperku/AutoGPT/AutoCAD 2018 [64bit] Pre Release Incl Keygen X FORCE [MUMBAI TPB].epub !!EXCLUSIVE!!.md deleted file mode 100644 index 1a2c30d907a5e3d7d150452b2b43911b85e95f6f..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/AutoCAD 2018 [64bit] Pre Release Incl Keygen X FORCE [MUMBAI TPB].epub !!EXCLUSIVE!!.md +++ /dev/null @@ -1,6 +0,0 @@ -

    AutoCAD 2018 [64bit] Pre Release Incl Keygen X FORCE [MUMBAI TPB].epub


    Download Zip ⇒⇒⇒ https://gohhs.com/2uFUVW



    -
    - 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/diacanFperku/AutoGPT/Jennifer Lopez-Brave Full Album Zip.md b/spaces/diacanFperku/AutoGPT/Jennifer Lopez-Brave Full Album Zip.md deleted file mode 100644 index 55084044d141ce5d2abfc5379561578ae22ca159..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Jennifer Lopez-Brave Full Album Zip.md +++ /dev/null @@ -1,26 +0,0 @@ -
    -

    Review: Jennifer Lopez's Brave Full Album Zip

    -

    Jennifer Lopez, also known as J.Lo, is one of the most successful and versatile artists in the music industry. She has sold over 70 million records worldwide and has won numerous awards, including a Grammy nomination, a Golden Globe nomination, and four MTV Video Music Awards. She is also an actress, dancer, producer, fashion designer, and businesswoman.

    -

    Jennifer Lopez-Brave Full Album Zip


    DOWNLOAD · https://gohhs.com/2uFUJI



    -

    One of her most underrated albums is Brave, which was released in 2007. It is her sixth studio album and features a mix of pop, R&B, dance, and hip-hop genres. The album showcases Lopez's vocal range and emotional expression, as well as her ability to experiment with different sounds and styles. The album received mixed reviews from critics, but it was praised by fans for its diversity and creativity.

    -

    The album consists of 13 tracks, with a total duration of 47 minutes and 38 seconds. The album zip file can be downloaded from various online platforms, such as SoundCloud[^2^] [^3^] or YouTube[^1^]. Some of the highlights of the album are:

    -
      -
    • Stay Together: A catchy and upbeat pop song that encourages couples to stay together despite the challenges they face.
    • -
    • Forever: A romantic and soulful ballad that expresses Lopez's devotion and commitment to her lover.
    • -
    • Hold It Don't Drop It: A funky and groovy dance track that showcases Lopez's confident and sexy attitude.
    • -
    • Do It Well: A sassy and energetic hip-hop song that features a guest rap by Ludacris. It is one of the lead singles of the album and was a commercial success.
    • -
    • Gotta Be There: A smooth and mellow R&B song that samples Michael Jackson's classic hit "I Wanna Be Where You Are".
    • -
    • Never Gonna Give Up: A powerful and inspirational anthem that reflects Lopez's personal struggles and achievements.
    • -
    • Mile In These Shoes: A fierce and empowering rock song that celebrates Lopez's individuality and strength.
    • -
    • The Way It Is: A reflective and emotional ballad that deals with the realities of life and love.
    • -
    • Be Mine: A sweet and tender pop song that expresses Lopez's desire to be with her lover.
    • -
    • I Need Love: A passionate and sensual R&B song that features a guest appearance by Fabolous. It is one of the bonus tracks of the album.
    • -
    -

    Jennifer Lopez's Brave Full Album Zip is a must-have for any fan of her music. It is a diverse and creative album that showcases her talent and versatility as an artist. It is also a brave and honest album that reveals her personal feelings and experiences. Whether you are looking for a catchy pop song, a romantic ballad, or a funky dance track, you will find it in this album.

    - -

    Brave received a mixed reception from music critics, who praised Lopez's vocals and some of the production, but criticized the album's lack of originality and personality. Some critics also noted that the album did not reflect Lopez's current status as a married woman and a mother-to-be, as she was pregnant with twins during the album's release. [^1^] The album was also a commercial disappointment, becoming Lopez's lowest-selling album to date. It debuted at number 12 on the US Billboard 200 chart, with first-week sales of 53,000 copies, and dropped out of the chart after nine weeks. [^1^] It also failed to reach the top ten in any other major market, except for Canada and Japan, where it peaked at number nine and number seven, respectively. [^1^] The album has sold only 650,000 copies worldwide as of 2015. [^1^]

    -

    -

    Lopez promoted the album with several live performances on television shows and award ceremonies, such as Good Morning America , The Ellen DeGeneres Show , Fashion Rocks , and the American Music Awards . She also embarked on a co-headlining tour with her husband Marc Anthony , called the Jennifer Lopez and Marc Anthony en Concierto , which ran from September to November 2007. The tour consisted of 28 shows across North America and featured songs from both Brave and Como Ama una Mujer , as well as some of Lopez's previous hits. The tour received positive reviews from critics and fans, who praised Lopez's stage presence and energy. [^1^]

    -

    Brave is an album that showcases Lopez's versatility and talent as a singer and performer, but it also suffers from a lack of innovation and identity. It is an album that tries to please everyone, but ends up pleasing no one. It is an album that reflects Lopez's happiness and contentment in her personal life, but it also fails to capture her charisma and passion as an artist. It is an album that deserves more recognition and appreciation, but it also needs more courage and creativity.

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/dilums/sentence-similarity/app/globals.css b/spaces/dilums/sentence-similarity/app/globals.css deleted file mode 100644 index 0b46ea13c87edb4efec8118b5e47b06c194eb49f..0000000000000000000000000000000000000000 --- a/spaces/dilums/sentence-similarity/app/globals.css +++ /dev/null @@ -1,76 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -@layer base { - :root { - --background: 0 0% 100%; - --foreground: 240 10% 3.9%; - - --card: 0 0% 100%; - --card-foreground: 240 10% 3.9%; - - --popover: 0 0% 100%; - --popover-foreground: 240 10% 3.9%; - - --primary: 240 5.9% 10%; - --primary-foreground: 0 0% 98%; - - --secondary: 240 4.8% 95.9%; - --secondary-foreground: 240 5.9% 10%; - - --muted: 240 4.8% 95.9%; - --muted-foreground: 240 3.8% 46.1%; - - --accent: 240 4.8% 95.9%; - --accent-foreground: 240 5.9% 10%; - - --destructive: 0 84.2% 60.2%; - --destructive-foreground: 0 0% 98%; - - --border: 240 5.9% 90%; - --input: 240 5.9% 90%; - --ring: 240 10% 3.9%; - - --radius: 0.5rem; - } - - .dark { - --background: 240 10% 3.9%; - --foreground: 0 0% 98%; - - --card: 240 10% 3.9%; - --card-foreground: 0 0% 98%; - - --popover: 240 10% 3.9%; - --popover-foreground: 0 0% 98%; - - --primary: 0 0% 98%; - --primary-foreground: 240 5.9% 10%; - - --secondary: 240 3.7% 15.9%; - --secondary-foreground: 0 0% 98%; - - --muted: 240 3.7% 15.9%; - --muted-foreground: 240 5% 64.9%; - - --accent: 240 3.7% 15.9%; - --accent-foreground: 0 0% 98%; - - --destructive: 0 62.8% 30.6%; - --destructive-foreground: 0 0% 98%; - - --border: 240 3.7% 15.9%; - --input: 240 3.7% 15.9%; - --ring: 240 4.9% 83.9%; - } -} - -@layer base { - * { - @apply border-border; - } - body { - @apply bg-background text-foreground; - } -} \ No newline at end of file diff --git a/spaces/djgoettel/01-3DModel-GradioDemo/README.md b/spaces/djgoettel/01-3DModel-GradioDemo/README.md deleted file mode 100644 index 7d78d2fde869c946af10292d3c031a53b6478ba4..0000000000000000000000000000000000000000 --- a/spaces/djgoettel/01-3DModel-GradioDemo/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 01 3DModel GradioDemo -emoji: 🦆🧊 -colorFrom: red -colorTo: gray -sdk: gradio -sdk_version: 3.3.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 diff --git a/spaces/dog/fastapi-document-qa/Dockerfile b/spaces/dog/fastapi-document-qa/Dockerfile deleted file mode 100644 index 37c77ed00c211f975a724eaa23aa107b9acfc42a..0000000000000000000000000000000000000000 --- a/spaces/dog/fastapi-document-qa/Dockerfile +++ /dev/null @@ -1,31 +0,0 @@ -# Use the official Python 3.9 image -FROM python:3.9 - -RUN apt-get update && apt-get install -y \ - tesseract-ocr-all \ - && rm -rf /var/lib/apt/lists/* - -# Set the working directory to /code -WORKDIR /code - -# Copy the current directory contents into the container at /code -COPY ./requirements.txt /code/requirements.txt - -# Install requirements.txt -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -# 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 - -# Set the working directory to the user's home directory -WORKDIR $HOME/app - -# Copy the current directory contents into the container at $HOME/app setting the owner to the user -COPY --chown=user . $HOME/app - -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"] \ No newline at end of file diff --git a/spaces/dolceschokolade/chatbot-mini/components/Chat/PluginSelect.tsx b/spaces/dolceschokolade/chatbot-mini/components/Chat/PluginSelect.tsx deleted file mode 100644 index effdbd67441760d97b4e533fc6098430a1c9af26..0000000000000000000000000000000000000000 --- a/spaces/dolceschokolade/chatbot-mini/components/Chat/PluginSelect.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { FC, useEffect, useRef } from 'react'; - -import { useTranslation } from 'next-i18next'; - -import { Plugin, PluginList } from '@/types/plugin'; - -interface Props { - plugin: Plugin | null; - onPluginChange: (plugin: Plugin) => void; - onKeyDown: (e: React.KeyboardEvent) => void; -} - -export const PluginSelect: FC = ({ - plugin, - onPluginChange, - onKeyDown, -}) => { - const { t } = useTranslation('chat'); - - const selectRef = useRef(null); - - const handleKeyDown = (e: React.KeyboardEvent) => { - const selectElement = selectRef.current; - const optionCount = selectElement?.options.length || 0; - - if (e.key === '/' && e.metaKey) { - e.preventDefault(); - if (selectElement) { - selectElement.selectedIndex = - (selectElement.selectedIndex + 1) % optionCount; - selectElement.dispatchEvent(new Event('change')); - } - } else if (e.key === '/' && e.shiftKey && e.metaKey) { - e.preventDefault(); - if (selectElement) { - selectElement.selectedIndex = - (selectElement.selectedIndex - 1 + optionCount) % optionCount; - selectElement.dispatchEvent(new Event('change')); - } - } else if (e.key === 'Enter') { - e.preventDefault(); - if (selectElement) { - selectElement.dispatchEvent(new Event('change')); - } - - onPluginChange( - PluginList.find( - (plugin) => - plugin.name === selectElement?.selectedOptions[0].innerText, - ) as Plugin, - ); - } else { - onKeyDown(e); - } - }; - - useEffect(() => { - if (selectRef.current) { - selectRef.current.focus(); - } - }, []); - - return null; -}; diff --git a/spaces/dongyaren/12345/README.md b/spaces/dongyaren/12345/README.md deleted file mode 100644 index e09b782ed3f8ebeea03e8b824507aa18ff18b9d1..0000000000000000000000000000000000000000 --- a/spaces/dongyaren/12345/README.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: bingo -emoji: 😊 -colorFrom: red -colorTo: red -sdk: docker -pinned: true -license: mit ---- - -
    - -# Bingo - -Bingo,一个让你呼吸顺畅 New Bing。 - -高度还原 New Bing 网页版的主要操作,国内可用,兼容绝大多数微软 Bing AI 的功能,可自行部署使用。 - -![Github stars](https://badgen.net/github/stars/weaigc/bingo?icon=github&label=stars) -![Gthub issues](https://img.shields.io/github/issues/weaigc/bingo) -[![docker build](https://github.com/weaigc/bingo/actions/workflows/docker.yml/badge.svg)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![docker hub](https://badgen.net/docker/size/weaigc/bingo?icon=docker&label=image%20size)](https://hub.docker.com/repository/docker/weaigc/bingo/) -[![MIT License](https://img.shields.io/badge/license-MIT-97c50f)](https://github.com/weaigc/bingo/blob/main/license) - -问题反馈请前往 https://github.com/weaigc/bingo/issues -
    - - diff --git a/spaces/dtrejopizzo/texto-a-imagenes-intel/app.py b/spaces/dtrejopizzo/texto-a-imagenes-intel/app.py deleted file mode 100644 index 8174c75a7342ab9f04cb7403caf5f9ac67cc8a3d..0000000000000000000000000000000000000000 --- a/spaces/dtrejopizzo/texto-a-imagenes-intel/app.py +++ /dev/null @@ -1,150 +0,0 @@ -import os -import gradio as gr -import numpy as np -import random -import torch -import subprocess -import time -import requests -import json - -import base64 -from io import BytesIO -from PIL import Image - -url = "http://107.23.90.209:80" - -print('=='*20) -print(os.system("hostname -i")) - -def img2img_generate(source_img, prompt, steps=25, strength=0.75, seed=42, guidance_scale=7.5, hidden=""): - - if hidden != os.environ["front_token"]: - return None - - # cpu info - # print(subprocess.check_output(["cat /proc/cpuinfo | grep 'model name' |uniq"], stderr=subprocess.STDOUT).decode("utf8")) - print('image-to-image') - print("prompt: ", prompt) - print("steps: ", steps) - buffered = BytesIO() - source_img.save(buffered, format="JPEG") - img_b64 = base64.b64encode(buffered.getvalue()) - - data = {"source_img": img_b64.decode(), "prompt": prompt, "steps": steps, - "guidance_scale": guidance_scale, "seed": seed, "strength": strength, - "token": os.environ["access_token"]} - - start_time = time.time() - resp = requests.post(url, data=json.dumps(data)) - - try: - img_str = json.loads(resp.text)["img_str"] - print("compute node: ", json.loads(resp.text)["ip"]) - except: - print('no inference result. please check server connection') - return None - - img_byte = base64.b64decode(img_str) - img_io = BytesIO(img_byte) # convert image to file-like object - img = Image.open(img_io) # img is now PIL Image object - print("elapsed time: ", time.time() - start_time) - return img - - -def txt2img_generate(prompt, steps=25, seed=42, guidance_scale=7.5, hidden=""): - - if hidden != os.environ["front_token"]: - return None - - # cpu info - # print(subprocess.check_output(["cat /proc/cpuinfo | grep 'model name' |uniq"], stderr=subprocess.STDOUT).decode("utf8")) - print('text-to-image') - print("prompt: ", prompt) - print("steps: ", steps) - data = {"prompt": prompt, - "steps": steps, "guidance_scale": guidance_scale, "seed": seed, - "token": os.environ["access_token"]} - start_time = time.time() - resp = requests.post(url, data=json.dumps(data)) - try: - img_str = json.loads(resp.text)["img_str"] - print("compute node: ", json.loads(resp.text)["ip"]) - except: - print('no inference result. please check server connection') - return None - - img_byte = base64.b64decode(img_str) - img_io = BytesIO(img_byte) # convert image to file-like object - img = Image.open(img_io) # img is now PIL Image object - print("elapsed time: ", time.time() - start_time) - return img - -md = """ -This demo shows the accelerated inference performance of a Stable Diffusion model on **Intel Xeon Gold 64xx (4th Gen Intel Xeon Scalable Processors codenamed Sapphire Rapids)**. Try it and generate photorealistic images from text! -You may also want to try creating your own Stable Diffusion model with few-shot fine-tuning. Please refer to our blog and code available in Intel Neural Compressor and Hugging Face Diffusers. -""" - -legal = """ -Performance varies by use, configuration and other factors. Learn more at www.Intel.com/PerformanceIndex. Performance results are based on testing as of dates shown in configurations and may not reflect all publicly available updates. See backup for configuration details. No product or component can be absolutely secure. -© Intel Corporation. Intel, the Intel logo, and other Intel marks are trademarks of Intel Corporation or its subsidiaries. Other names and brands may be claimed as the property of others. -""" - -details = """ -4th Gen Intel Xeon Scalable Processor Inference. Test by Intel on 01/06/2023. 1 node, 1S, Intel(R) Xeon(R) Gold 64xx CPU @ 3.0GHz 32 cores and software with 512GB (8x64GB DDR5 4800 MT/s [4800 MT/s]), microcode 0x2a000080, HT on, Turbo on, Ubuntu 22.04.1 LTS, 5.15.0-1026-aws, 200G Amazon Elastic Block Store. Multiple nodes connected with Elastic Network Adapter (ENA). PyTorch Nightly build (2.0.0.dev20230105+cpu), Transformers 4.25.1, Diffusers 0.11.1, oneDNN v2.7.2. -""" - -css = ''' - .instruction{position: absolute; top: 0;right: 0;margin-top: 0px !important} - .arrow{position: absolute;top: 0;right: -110px;margin-top: -8px !important} - #component-4, #component-3, #component-10{min-height: 0} - .duplicate-button img{margin: 0} -''' - -random_seed = random.randint(0, 2147483647) - -with gr.Blocks(css=css) as demo: - gr.Markdown("# Stable Diffusion Inference Demo on 4th Gen Intel Xeon Scalable Processors") - gr.Markdown(md) - - with gr.Tab("Text-to-Image"): - with gr.Row() as text_to_image: - with gr.Column(): - prompt = gr.inputs.Textbox(label='Prompt', default='a photo of an astronaut riding a horse on mars') - inference_steps = gr.inputs.Slider(1, 100, label='Inference Steps - increase the steps for better quality (e.g., avoiding black image) ', default=20, step=1) - seed = gr.inputs.Slider(0, 2147483647, label='Seed', default=random_seed, step=1) - guidance_scale = gr.inputs.Slider(1.0, 20.0, label='Guidance Scale - how much the prompt will influence the results', default=7.5, step=0.1) - hidden = gr.Textbox(label='hidden', value=os.environ["front_token"], visible=False) - txt2img_button = gr.Button("Generate Image") - - with gr.Column(): - result_image = gr.Image() - - - with gr.Tab("Image-to-Image text-guided generation"): - with gr.Row() as image_to_image: - with gr.Column(): - source_img = gr.Image(source="upload", type="pil", value="https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg") - # source_img = gr.Image(source="upload", type="pil") - prompt_2 = gr.inputs.Textbox(label='Prompt', default='A fantasy landscape, trending on artstation') - inference_steps_2 = gr.inputs.Slider(1, 100, label='Inference Steps - increase the steps for better quality (e.g., avoiding black image) ', default=20, step=1) - seed_2 = gr.inputs.Slider(0, 2147483647, label='Seed', default=random_seed, step=1) - guidance_scale_2 = gr.inputs.Slider(1.0, 20.0, label='Guidance Scale - how much the prompt will influence the results', default=7.5, step=0.1) - strength = gr.inputs.Slider(0.0, 1.0, label='Strength - adding more noise to it the larger the strength', default=0.75, step=0.01) - hidden_2 = gr.Textbox(label='hidden', value=os.environ["front_token"], visible=False) - img2img_button = gr.Button("Generate Image") - - with gr.Column(): - result_image_2 = gr.Image() - - - txt2img_button.click(fn=txt2img_generate, inputs=[prompt, inference_steps, seed, guidance_scale, hidden], outputs=result_image, queue=False) - img2img_button.click(fn=img2img_generate, inputs=[source_img, prompt_2, inference_steps_2, strength, seed_2, guidance_scale_2, hidden_2], outputs=result_image_2, queue=False) - - gr.Markdown("**Additional Test Configuration Details:**") - gr.Markdown(details) - - gr.Markdown("**Notices and Disclaimers:**") - gr.Markdown(legal) - -demo.queue(default_enabled=False).launch(debug=True) \ No newline at end of file diff --git a/spaces/eaglelandsonce/simplevectorization/utils.py b/spaces/eaglelandsonce/simplevectorization/utils.py deleted file mode 100644 index ba2696f8b8d51a1ddb57eb97a6375fea01671915..0000000000000000000000000000000000000000 --- a/spaces/eaglelandsonce/simplevectorization/utils.py +++ /dev/null @@ -1,10 +0,0 @@ -import os -from langchain.embeddings import OpenAIEmbeddings - - -# Function to generate title and Logline from simple chaining -def generate_vector(prompt, api_key): - os.environ["OPENAI_API_KEY"] = api_key - embeddings = OpenAIEmbeddings() - text_embedding = embeddings.embed_query(prompt) - return text_embedding diff --git a/spaces/emc348/faces-through-time/run_pti.py b/spaces/emc348/faces-through-time/run_pti.py deleted file mode 100644 index 8639b8a623a0525038dc8484d7a1946e0219cf9b..0000000000000000000000000000000000000000 --- a/spaces/emc348/faces-through-time/run_pti.py +++ /dev/null @@ -1,55 +0,0 @@ -from random import choice -from string import ascii_uppercase -from torch.utils.data import DataLoader -from torchvision.transforms import transforms -import os - -import sys -from configs import global_config, paths_config - -from training.coaches.multi_id_coach import MultiIDCoach -from training.coaches.single_id_coach import SingleIDCoach -from utils.ImagesDataset import ImagesDataset - - -def run_PTI(run_name="", in_year="2010", use_wandb=False, use_multi_id_training=False): - os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" - os.environ["CUDA_VISIBLE_DEVICES"] = global_config.cuda_visible_devices - - if run_name == "": - global_config.run_name = "".join(choice(ascii_uppercase) for i in range(12)) - else: - global_config.run_name = run_name - global_config.pivotal_training_steps = 1 - global_config.training_step = 1 - - embedding_dir_path = f"{paths_config.embedding_base_dir}/{paths_config.input_data_id}/{paths_config.pti_results_keyword}" - os.makedirs(embedding_dir_path, exist_ok=True) - - dataset = ImagesDataset( - paths_config.input_data_path, - transforms.Compose( - [ - transforms.Resize((256, 256)), - transforms.ToTensor(), - transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), - ] - ), - ) - - dataloader = DataLoader(dataset, batch_size=1, shuffle=False) - - if use_multi_id_training: - coach = MultiIDCoach(dataloader, in_year, use_wandb) - else: - coach = SingleIDCoach(dataloader, in_year, use_wandb) - - coach.train() - - return global_config.run_name - - -if __name__ == "__main__": - run_name = f"pti" - print(run_name) - run_PTI(run_name=run_name, in_year="2010", use_wandb=False, use_multi_id_training=False) diff --git a/spaces/ericmichael/openai-playground-utrgv/examples.py b/spaces/ericmichael/openai-playground-utrgv/examples.py deleted file mode 100644 index 371b80af5d82fae10830c953f0670fb968b8ad45..0000000000000000000000000000000000000000 --- a/spaces/ericmichael/openai-playground-utrgv/examples.py +++ /dev/null @@ -1,67 +0,0 @@ -def load_examples(additional=[]): - return [ - {"name": "none", "system_message": "", "message": ""}, - {"name": "Q&A", "system_message": """ -You are a highly intelligent question answering bot. If you are asked a question that is rooted in truth, you will give you the answer. If you are asked a question that is nonsense, trickery, or has no clear answer, you will respond with "Unknown". - -For example: -Q: What is human life expectancy in the United States? -A: Human life expectancy in the United States is 78 years. - -Q: Who was president of the United States in 1955? -A: Dwight D. Eisenhower was president of the United States in 1955. - -Q: Which party did he belong to? -A: He belonged to the Republican Party. - -Q: What is the square root of banana? -A: Unknown - -Q: How does a telescope work? -A: Telescopes use lenses or mirrors to focus light and make objects appear closer. - -Q: Where were the 1992 Olympics held? -A: The 1992 Olympics were held in Barcelona, Spain. - -Q: How many squigs are in a bonk? -A: Unknown""", "message": "Where is the Valley of Kings?"}, - - {"name": "Grammar correction", "system_message": """ -You are an assistant that aids in correcting text to standard English. When given a sentence, reply with the corrected sentence. -If the sentence was already correct, repeat the sentence back. Do not provide any additional narrative.""", "message": "I no did my homework."}, - - {"name": "Summarize for a 2nd grader", "system_message": """ -You are an assistant that can summarize complex topics down for second-grade students. -""", "message": "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus."}, - - {"name": "Natural language to SQL", "system_message": """ -You are an AI Assistant that can convert natural language into syntactically valid SQL. - -Only consider the following schema: - -### Postgres SQL tables, with their properties: -# -# Employee(id, name, department_id) -# Department(id, name, address) -# Salary_Payments(id, employee_id, amount, date) -# -### -SELECT""", "message": "A query to list the names of the departments which employed more than 10 employees in the last 3 months"}, - {"name": "Parse unstructured data", "system_message": """ -There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy. There are also loheckles, which are a grayish blue fruit and are very tart, a little bit like a lemon. Pounits are a bright green color and are more savory than sweet. There are also plenty of loopnovas which are a neon pink flavor and taste like cotton candy. Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them. -""", "message": "Create a table extracting the fruit, color, and flavors from from Goocrux."}, - - {"name": "Python to natural language", "system_message": """ -You are an AI Assistant that is trained to convert Python to natural language. -When the user hands you a block of code, provide them an explanation of what the code does.""", -"message": """# Python 3 -def remove_common_prefix(x, prefix, ws_prefix): - x["completion"] = x["completion"].str[len(prefix) :] - if ws_prefix: - # keep the single whitespace as prefix - x["completion"] = " " + x["completion"] -return x -"""}, - {"name": "Keywords", "system_message": """ -You are an AI assistant trained to extract keywords from text.""", "message": "Black-on-black ware is a 20th- and 21st-century pottery tradition developed by the Puebloan Native American ceramic artists in Northern New Mexico. Traditional reduction-fired blackware has been made for centuries by pueblo artists. Black-on-black ware of the past century is produced with a smooth surface, with the designs applied through selective burnishing or the application of refractory slip. Another style involves carving or incising designs and selectively polishing the raised areas. For generations several families from Kha'po Owingeh and P'ohwhóge Owingeh pueblos have been making black-on-black ware with the techniques passed down from matriarch potters. Artists from other pueblos have also produced black-on-black ware. Several contemporary artists have created works honoring the pottery of their ancestors."}, -] + additional \ No newline at end of file diff --git a/spaces/etweedy/Find_objects/README.md b/spaces/etweedy/Find_objects/README.md deleted file mode 100644 index 1c17d300261891c274d90993bb9b86d35d06a7af..0000000000000000000000000000000000000000 --- a/spaces/etweedy/Find_objects/README.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Find Objects -emoji: 🔍 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.12.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 - -This app allows the user the use an example photo or upload their own photo, and attempts to recognize any of the following objects in the photo: -'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' - -The predictions are made by a multi-class pretrained ResNet50 model which was fine-tuned on the PASCAL Visual Object Classes Challenge 2007 dataset: -http://host.robots.ox.ac.uk/pascal/VOC/voc2007/index.html diff --git "a/spaces/f2api/gpt-academic/crazy_functions/\346\211\271\351\207\217\346\200\273\347\273\223PDF\346\226\207\346\241\243pdfminer.py" "b/spaces/f2api/gpt-academic/crazy_functions/\346\211\271\351\207\217\346\200\273\347\273\223PDF\346\226\207\346\241\243pdfminer.py" deleted file mode 100644 index ffbb05599ef09c9de25334ebeca2eef8022b9aaf..0000000000000000000000000000000000000000 --- "a/spaces/f2api/gpt-academic/crazy_functions/\346\211\271\351\207\217\346\200\273\347\273\223PDF\346\226\207\346\241\243pdfminer.py" +++ /dev/null @@ -1,160 +0,0 @@ -from toolbox import update_ui -from toolbox import CatchException, report_execption, write_results_to_file -from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive - -fast_debug = False - -def readPdf(pdfPath): - """ - 读取pdf文件,返回文本内容 - """ - import pdfminer - from pdfminer.pdfparser import PDFParser - from pdfminer.pdfdocument import PDFDocument - from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed - from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter - from pdfminer.pdfdevice import PDFDevice - from pdfminer.layout import LAParams - from pdfminer.converter import PDFPageAggregator - - fp = open(pdfPath, 'rb') - - # Create a PDF parser object associated with the file object - parser = PDFParser(fp) - - # Create a PDF document object that stores the document structure. - # Password for initialization as 2nd parameter - document = PDFDocument(parser) - # Check if the document allows text extraction. If not, abort. - if not document.is_extractable: - raise PDFTextExtractionNotAllowed - - # Create a PDF resource manager object that stores shared resources. - rsrcmgr = PDFResourceManager() - - # Create a PDF device object. - # device = PDFDevice(rsrcmgr) - - # BEGIN LAYOUT ANALYSIS. - # Set parameters for analysis. - laparams = LAParams( - char_margin=10.0, - line_margin=0.2, - boxes_flow=0.2, - all_texts=False, - ) - # Create a PDF page aggregator object. - device = PDFPageAggregator(rsrcmgr, laparams=laparams) - # Create a PDF interpreter object. - interpreter = PDFPageInterpreter(rsrcmgr, device) - - # loop over all pages in the document - outTextList = [] - for page in PDFPage.create_pages(document): - # read the page into a layout object - interpreter.process_page(page) - layout = device.get_result() - for obj in layout._objs: - if isinstance(obj, pdfminer.layout.LTTextBoxHorizontal): - # print(obj.get_text()) - outTextList.append(obj.get_text()) - - return outTextList - - -def 解析Paper(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt): - import time, glob, os - from bs4 import BeautifulSoup - print('begin analysis on:', file_manifest) - for index, fp in enumerate(file_manifest): - if ".tex" in fp: - with open(fp, 'r', encoding='utf-8', errors='replace') as f: - file_content = f.read() - if ".pdf" in fp.lower(): - file_content = readPdf(fp) - file_content = BeautifulSoup(''.join(file_content), features="lxml").body.text.encode('gbk', 'ignore').decode('gbk') - - prefix = "接下来请你逐文件分析下面的论文文件,概括其内容" if index==0 else "" - i_say = prefix + f'请对下面的文章片段用中文做一个概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{file_content}```' - i_say_show_user = prefix + f'[{index}/{len(file_manifest)}] 请对下面的文章片段做一个概述: {os.path.abspath(fp)}' - chatbot.append((i_say_show_user, "[Local Message] waiting gpt response.")) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - if not fast_debug: - msg = '正常' - # ** gpt request ** - gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive( - inputs=i_say, - inputs_show_user=i_say_show_user, - llm_kwargs=llm_kwargs, - chatbot=chatbot, - history=[], - sys_prompt="总结文章。" - ) # 带超时倒计时 - chatbot[-1] = (i_say_show_user, gpt_say) - history.append(i_say_show_user); history.append(gpt_say) - yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面 - if not fast_debug: time.sleep(2) - - all_file = ', '.join([os.path.relpath(fp, project_folder) for index, fp in enumerate(file_manifest)]) - i_say = f'根据以上你自己的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一段英文摘要(包括{all_file})。' - chatbot.append((i_say, "[Local Message] waiting gpt response.")) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - if not fast_debug: - msg = '正常' - # ** gpt request ** - gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive( - inputs=i_say, - inputs_show_user=i_say, - llm_kwargs=llm_kwargs, - chatbot=chatbot, - history=history, - sys_prompt="总结文章。" - ) # 带超时倒计时 - chatbot[-1] = (i_say, gpt_say) - history.append(i_say); history.append(gpt_say) - yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面 - res = write_results_to_file(history) - chatbot.append(("完成了吗?", res)) - yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面 - - - -@CatchException -def 批量总结PDF文档pdfminer(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - history = [] # 清空历史,以免输入溢出 - import glob, os - - # 基本信息:功能、贡献者 - chatbot.append([ - "函数插件功能?", - "批量总结PDF文档,此版本使用pdfminer插件,带token约简功能。函数插件贡献者: Euclid-Jie。"]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - - # 尝试导入依赖,如果缺少依赖,则给出安装建议 - try: - import pdfminer, bs4 - except: - report_execption(chatbot, history, - a = f"解析项目: {txt}", - b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pdfminer beautifulsoup4```。") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - if os.path.exists(txt): - project_folder = txt - else: - if txt == "": txt = '空空如也的输入栏' - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \ - [f for f in glob.glob(f'{project_folder}/**/*.pdf', recursive=True)] # + \ - # [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \ - # [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)] - if len(file_manifest) == 0: - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex或pdf文件: {txt}") - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - yield from 解析Paper(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt) - diff --git a/spaces/facebook/ov-seg/open_vocab_seg/utils/__init__.py b/spaces/facebook/ov-seg/open_vocab_seg/utils/__init__.py deleted file mode 100644 index dcf832dce405bbdcf45f2534a782494b37760cd9..0000000000000000000000000000000000000000 --- a/spaces/facebook/ov-seg/open_vocab_seg/utils/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# Copyright (c) Meta Platforms, Inc. All Rights Reserved - -from .events import setup_wandb, WandbWriter -from .predictor import VisualizationDemo, SAMVisualizationDemo \ No newline at end of file diff --git a/spaces/falterWliame/Face_Mask_Detection/Farming Simulator 2010 Gold Edition Torrent Download.html PATCHED.md b/spaces/falterWliame/Face_Mask_Detection/Farming Simulator 2010 Gold Edition Torrent Download.html PATCHED.md deleted file mode 100644 index 9463a53f25f6b6db2b1a42a3ed1a93ff562b84f7..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Farming Simulator 2010 Gold Edition Torrent Download.html PATCHED.md +++ /dev/null @@ -1,18 +0,0 @@ - -

    Farming Simulator 2010 Gold Edition Torrent Download

    -

    If you are looking for a realistic and immersive farming simulation game, you might want to check out Farming Simulator 2010 Gold Edition. This game lets you experience the life of a farmer, from planting crops to harvesting them, from raising animals to selling their products, and from managing your farm to expanding it.

    -

    Farming Simulator 2010 Gold Edition is the enhanced version of the original Farming Simulator 2010, which was released in 2009. It includes new features, such as new vehicles, new crops, new maps, new missions, and more. You can also download additional content from the official website or from the modding community.

    -

    Farming Simulator 2010 Gold Edition Torrent Download.html


    Download File ››››› https://urlca.com/2uDcta



    -

    To download Farming Simulator 2010 Gold Edition torrent, you need to have a torrent client installed on your computer, such as BitTorrent or uTorrent. You can find the torrent file from various sources online, but be careful of fake or malicious links. Always scan the file before opening it and make sure it is safe and legal.

    -

    Farming Simulator 2010 Gold Edition is a fun and relaxing game that will keep you entertained for hours. You can play it solo or with your friends online. You can also customize your game with mods and create your own scenarios. If you love farming and simulation games, you should definitely give Farming Simulator 2010 Gold Edition a try.

    - -

    One of the best features of Farming Simulator 2010 Gold Edition is the realistic physics and graphics. You can see the details of your crops, animals, vehicles, and environment. You can also feel the effects of weather, seasons, and soil conditions. You have to adapt your farming strategies accordingly and plan ahead.

    -

    Another great feature of Farming Simulator 2010 Gold Edition is the variety of options and activities. You can choose from different types of crops, such as wheat, corn, potatoes, and more. You can also raise different types of animals, such as cows, sheep, chickens, and more. You can sell your products at the market or use them for other purposes, such as feeding your animals or making biofuel. You can also buy new equipment and vehicles, such as tractors, harvesters, plows, and more. You can also hire workers to help you with your tasks or do them yourself.

    -

    Farming Simulator 2010 Gold Edition is a game that will appeal to both casual and hardcore gamers. It is easy to learn but hard to master. It is relaxing but challenging. It is realistic but fun. It is a game that will make you appreciate the work and joy of farming.

    - -

    If you want to play Farming Simulator 2010 Gold Edition online with your friends, you can join or create a multiplayer session. You can cooperate or compete with other players in various modes, such as free play, team play, or mission mode. You can also chat with other players and share your farming tips and tricks.

    -

    Farming Simulator 2010 Gold Edition also supports modding, which means you can download or create your own content for the game. You can find thousands of mods online, such as new vehicles, new crops, new maps, new missions, and more. You can also use the modding tools provided by the developers to create your own mods and share them with the community.

    -

    Farming Simulator 2010 Gold Edition is a game that will satisfy your farming fantasies. You can download it from various torrent sites, but make sure you have a good antivirus program and a reliable torrent client. You can also buy it from the official website or from other online stores. Farming Simulator 2010 Gold Edition is a game that will make you feel like a real farmer.

    -

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Call of Duty 1 APK Everything You Need to Know Before Playing.md b/spaces/fatiXbelha/sd/Call of Duty 1 APK Everything You Need to Know Before Playing.md deleted file mode 100644 index d233c59552215c1afd68ccdbe310a56b73efda85..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Call of Duty 1 APK Everything You Need to Know Before Playing.md +++ /dev/null @@ -1,136 +0,0 @@ -
    -

    Call of Duty 1 APK: How to Download and Play the Classic FPS on Your Android Device

    -

    If you are a fan of first-person shooter (FPS) games, you probably know about Call of Duty, one of the most popular and influential franchises in the genre. The first installment of the series, Call of Duty 1, was released in 2003 and set the standard for realistic and immersive war-themed gameplay. The game received critical acclaim and won several awards for its graphics, sound, and multiplayer mode.

    -

    call of duty 1 apk


    Download ››› https://urllie.com/2uNDdi



    -

    But did you know that you can play Call of Duty 1 on your Android device? Yes, you read that right. Thanks to an APK file, you can enjoy this classic game on your mobile phone or tablet. In this article, we will tell you everything you need to know about Call of Duty 1 APK, including what it is, how to download and install it, and some tips and tricks for playing it. Let's get started!

    -

    What is Call of Duty 1 APK?

    -

    A brief introduction to the game and its features

    -

    Call of Duty 1 APK is an Android version of the original Call of Duty game that was released for Windows, Mac OS X, and consoles. The game is set in World War II and follows the stories of three soldiers from different countries: an American paratrooper, a British commando, and a Soviet infantryman. The game features 24 missions that span various locations such as France, Germany, Russia, and North Africa.

    -

    The game offers a realistic and cinematic experience that immerses you in the chaos and horror of war. You will face enemy soldiers, tanks, planes, and artillery as you complete your objectives. You will also use a variety of weapons from different countries, such as rifles, pistols, grenades, bazookas, and flamethrowers. The game also has a multiplayer mode that allows you to play with or against other players online or via LAN.

    -

    call of duty 1 mobile apk download
    -call of duty 1 legends of war apk
    -call of duty 1 apk obb
    -call of duty 1 apk mod
    -call of duty 1 apk offline
    -call of duty 1 apk for android
    -call of duty 1 apk data
    -call of duty 1 apk free download
    -call of duty 1 apk latest version
    -call of duty 1 apk uptodown
    -call of duty 1 apk pure
    -call of duty 1 apk revdl
    -call of duty 1 apk andropalace
    -call of duty 1 apk rexdl
    -call of duty 1 apk highly compressed
    -call of duty 1 apk no verification
    -call of duty 1 apk hack
    -call of duty 1 apk unlimited money
    -call of duty 1 apk full version
    -call of duty 1 apk original
    -call of duty 1 apk mirror
    -call of duty 1 apk android oyun club
    -call of duty 1 apk + sd data
    -call of duty 1 apk + obb download for android
    -call of duty 1 apk + obb offline download
    -call of duty 1 apk + obb highly compressed download
    -call of duty 1 apk + obb mod menu download
    -call of duty 1 apk + obb latest update download
    -call of duty 1 apk + obb file download for android
    -call of duty 1 apk + obb file download for pc
    -call of duty 1 mobile beta apk download
    -call of duty 1 mobile global version apk download
    -call of duty 1 mobile chinese version apk download
    -call of duty 1 mobile zombies mode apk download
    -call of duty 1 mobile multiplayer mode apk download
    -call of duty 1 mobile battle royale mode apk download
    -call of duty 1 mobile hack version apk download
    -call of duty 1 mobile mod menu apk download
    -call of duty 1 mobile unlimited cp and credits apk download
    -call of duty 1 mobile god mode and aimbot apk download
    -how to install call of duty 1 apk on android phone
    -how to play call of duty 1 offline on android phone without internet connection
    -how to update call of duty 1 on android phone without losing progress
    -how to fix lag and crash issues in call of duty 1 on android phone
    -how to connect controller and keyboard to play call of duty 1 on android phone
    -how to get free cp and credits in call of duty 1 on android phone
    -how to unlock all weapons and skins in call of duty 1 on android phone
    -how to join clan and chat with friends in call of duty 1 on android phone
    -how to rank up fast and win every match in call of duty 1 on android phone

    -

    The benefits of playing Call of Duty 1 on your mobile device

    -

    Playing Call of Duty 1 on your Android device has several advantages over playing it on a PC or console. Here are some of them:

    -
      -
    • You can play it anytime and anywhere. You don't need a powerful computer or a TV screen to enjoy this game. You can just grab your phone or tablet and start shooting.
    • -
    • You can save space on your device. The APK file is only about 400 MB in size, which is much smaller than the original game that requires several GBs of storage space.
    • -
    • You can customize the game settings according to your preferences. You can adjust the graphics quality, sound volume, sensitivity, and other options to suit your device's capabilities and your personal taste.
    • -
    • You can experience nostalgia. If you played Call of Duty 1 when it came out, you will surely appreciate the opportunity to relive those memories on your mobile device. You will also notice how well the game has aged and how fun it still is.
    • -
    -

    How to download and install Call of Duty 1 APK?

    -

    The requirements and precautions for downloading the APK file

    -

    Before you download and install Call of Duty 1 APK, you need to make sure that your device meets some requirements and that you follow some precautions. Here are some things to keep in mind:

    -
      -
    • Your device must have Android 4.0 or higher - Your device must have at least 1 GB of RAM and 2 GB of free storage space - Your device must allow the installation of apps from unknown sources. You can enable this option in your device's settings, under security or privacy. - You must download the APK file from a trusted and verified source. There are many websites that offer APK files, but some of them may contain malware or viruses that can harm your device or steal your data. You should always check the reviews and ratings of the website before downloading anything from it. - You must have a stable and fast internet connection to download the APK file and to play the game online.
    • -
    -

    The steps to download and install the APK file from a reliable source

    -

    Once you have checked the requirements and precautions, you can proceed to download and install Call of Duty 1 APK on your device. Here are the steps to follow:

    -
      -
    1. Go to a reliable website that offers Call of Duty 1 APK, such as [APKPure] or [APKMirror]. You can use your browser or a search engine to find these websites.
    2. -
    3. On the website, find the Call of Duty 1 APK file and click on the download button. You may have to wait for a few seconds or minutes for the download to start.
    4. -
    5. Once the download is complete, locate the APK file on your device's file manager or downloads folder. Tap on the file to open it and start the installation process.
    6. -
    7. You may see a warning message that says "This type of file can harm your device". Ignore this message and tap on "Install anyway" or "Allow from this source". This will allow the installation of Call of Duty 1 APK on your device.
    8. -
    9. Wait for the installation to finish. You may see a progress bar or a confirmation message that says "App installed".
    10. -
    11. After the installation is done, you can find the Call of Duty 1 icon on your device's home screen or app drawer. Tap on it to launch the game and enjoy!
    12. -
    -

    How to launch and play the game on your Android device

    -

    Now that you have downloaded and installed Call of Duty 1 APK on your device, you are ready to play the game. Here are some tips on how to launch and play the game on your Android device:

    -
      -
    • When you launch the game, you may see a loading screen that says "Checking for updates". This is normal and it means that the game is checking for any patches or updates that may improve its performance or fix any bugs.
    • -
    • After the loading screen, you will see the main menu of the game. Here you can choose between single-player mode or multiplayer mode. You can also access the options menu where you can change the game settings, such as graphics, sound, controls, etc.
    • -
    • If you choose single-player mode, you will see a list of campaigns that you can play. Each campaign has several missions that follow a different soldier's story. You can select any campaign or mission that you want to play. You can also adjust the difficulty level according to your skill and preference.
    • -
    • If you choose multiplayer mode, you will see a list of servers that you can join. Each server has a different game mode, map, and number of players. You can select any server that suits your taste and join it. You can also create your own server and invite your friends to play with you.
    • -
    • Once you start playing, you will see a HUD (head-up display) that shows your health, ammo, weapon, compass, objectives, and other information. You can use the touch screen to move, aim, shoot, reload, switch weapons, throw grenades, crouch, jump, etc. You can also use voice chat to communicate with other players.
    • -
    -

    Tips and tricks for playing Call of Duty 1 APK

    -

    How to optimize the game settings for the best performance

    -

    Call of Duty 1 APK is a high-quality game that requires a lot of resources from your device. Therefore, you may experience some lagging or crashing issues if your device is not powerful enough or if your game settings are too high. To avoid these problems, you should optimize the game settings for the best performance. Here are some tips on how to do that:

    -
      -
    • Lower the graphics quality. This will reduce the amount of detail and texture in the game, but it will also improve the frame rate and smoothness of the game. You can lower the graphics quality in the options menu under graphics settings.
    • -
    • Turn off sound effects and music. This will reduce the amount of noise and distraction in the game, but it will also save some battery life and memory usage of your device. You can turn off sound effects and music in the options menu under sound settings.
    • -
    • Close other apps and background processes. This will free up some RAM and CPU power for the game, and prevent any interference or conflict with other apps. You can close other apps and background processes by using your device's task manager or by restarting your device before playing the game.
    • -
    -

    How to use the customizable and intuitive controls

    -

    Call of Duty 1 APK has a customizable and intuitive control system that allows you to play the game with ease and comfort. You can adjust the size, position, and sensitivity of the buttons and joysticks on the screen according to your preference. You can also choose between different control schemes, such as simple, advanced, or gyroscopic. Here are some tips on how to use the controls:

    -
      -
    • Use the left joystick to move your character. You can drag it in any direction to move forward, backward, left, or right. You can also double-tap it to sprint.
    • -
    • Use the right joystick to aim your weapon. You can drag it in any direction to look around and aim at your enemies. You can also tap it to zoom in or out.
    • -
    • Use the fire button to shoot your weapon. You can tap it once to fire a single shot, or hold it down to fire continuously. You can also swipe it up or down to switch between different firing modes, such as semi-automatic, burst, or full-automatic.
    • -
    • Use the reload button to reload your weapon. You can tap it once to reload your current weapon, or hold it down to switch to another weapon. You can also swipe it left or right to cycle through your available weapons.
    • -
    • Use the grenade button to throw a grenade. You can tap it once to throw a grenade in front of you, or hold it down to aim and adjust the distance and angle of your throw. You can also swipe it left or right to cycle through your available grenades.
    • -
    • Use the crouch button to crouch or stand up. You can tap it once to crouch, which will make you harder to hit and more accurate, or tap it again to stand up, which will make you faster and more mobile.
    • -
    • Use the jump button to jump over obstacles or gaps. You can tap it once to jump, which will help you avoid enemy fire and reach higher places.
    • -
    -

    How to master the different game modes and maps

    -

    Call of Duty 1 APK has a variety of game modes and maps that offer different challenges and experiences. You can play solo or with other players online or via LAN. Here are some tips on how to master the different game modes and maps:

    -
      -
    • Deathmatch: This is a free-for-all mode where you have to kill as many enemies as possible before the time runs out. The player with the most kills wins. To win this mode, you should be aggressive and fast, and use weapons that have high damage and rate of fire.
    • -
    • Team Deathmatch: This is a team-based mode where you have to work with your teammates to kill as many enemies as possible before the time runs out. The team with the most kills wins. To win this mode, you should communicate and coordinate with your teammates, and use weapons that suit your role and strategy.
    • -
    • Capture the Flag: This is a team-based mode where you have to capture the enemy's flag and bring it back to your base while defending your own flag from being captured. The team with the most flag captures wins. To win this mode, you should balance offense and defense, and use weapons that have high mobility and range.
    • -
    • Search and Destroy: This is a team-based mode where you have to either plant a bomb at one of the enemy's sites and detonate it, or defuse the bomb planted by the enemy before it explodes. The team that completes their objective wins. To win this mode, you should be stealthy and tactical, and use weapons that have high accuracy and power.
    • -
    • The game has 16 maps that are based on real-world locations from World War II, such as Stalingrad, Berlin, Omaha Beach, etc. Each map has different terrain, layout, size, and features that affect the gameplay. To master each map, you should explore and learn its routes, choke points, hiding spots, sniping spots, etc.
    • -
    -

    Conclusion

    -

    A summary of the main points and a call to action

    -

    In conclusion, Call of Duty 1 APK is an amazing way to play one of the best FPS games ever made on your Android device. You can enjoy a realistic and immersive war-themed gameplay that features 24 missions, various weapons , and multiplayer mode. You can also customize the game settings and controls to suit your device and preference. All you need to do is download and install the APK file from a reliable source and follow the steps we have provided in this article. You will be amazed by how well this game runs and looks on your mobile device.

    -

    So what are you waiting for? Download Call of Duty 1 APK today and experience the thrill and excitement of this classic game on your Android device. You will not regret it!

    -

    FAQs

    -

    Is Call of Duty 1 APK safe to download and install?

    -

    Yes, Call of Duty 1 APK is safe to download and install as long as you get it from a trusted and verified source. You should always check the reviews and ratings of the website before downloading anything from it. You should also scan the APK file with an antivirus or malware detector before installing it on your device.

    -

    Is Call of Duty 1 APK legal to use?

    -

    Yes, Call of Duty 1 APK is legal to use as long as you own a copy of the original game or have a license to play it. You should not use Call of Duty 1 APK to pirate or distribute the game without permission from the developers or publishers.

    -

    Does Call of Duty 1 APK require an internet connection to play?

    -

    No, Call of Duty 1 APK does not require an internet connection to play the single-player mode. However, you will need an internet connection to play the multiplayer mode or to download any updates or patches for the game.

    -

    Can I play Call of Duty 1 APK with a controller or a keyboard and mouse?

    -

    Yes, you can play Call of Duty 1 APK with a controller or a keyboard and mouse if your device supports them. You can connect your controller or keyboard and mouse via Bluetooth, USB, or OTG cable. You can also use an app like Octopus or Panda Gamepad Pro to map the buttons and keys to the game controls.

    -

    Can I play Call of Duty 1 APK with my friends?

    -

    Yes, you can play Call of Duty 1 APK with your friends online or via LAN. You can join or create a server and invite your friends to play with you. You can also chat with them using voice chat or text chat.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/DOP 2 Delete One Part - The Game That Tests Your Logic and Creativity.md b/spaces/fatiXbelha/sd/DOP 2 Delete One Part - The Game That Tests Your Logic and Creativity.md deleted file mode 100644 index fe35e9e53fe4b6fa5e7250711d1eac6e368f6145..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/DOP 2 Delete One Part - The Game That Tests Your Logic and Creativity.md +++ /dev/null @@ -1,99 +0,0 @@ - -

    DOP 2: Delete One Part - A Fun and Challenging Brain Game

    -

    Do you like brain games that make you think outside the box? Do you enjoy puzzles that test your logic and imagination? If you answered yes, then you will love DOP 2: Delete One Part, a popular brain game that has millions of downloads on Google Play and App Store.

    -

    dop 2


    Download Zip >>>>> https://urllie.com/2uNBho



    -

    DOP 2 is a sequel to the hit game DOP: Draw One Part, which was released in 2020 by SayGames Ltd, a leading developer of casual games. In this game, you have to swipe your finger across your phone screen to erase parts of the drawing and see what lies behind it. Sounds easy, right? Well, not quite. The game may seem simple, but it is full of tricky brain teasers that will keep you guessing.

    -

    In this article, we will tell you everything you need to know about DOP 2, including how to play it, tips and tricks for solving the puzzles, benefits of playing it, features of the game, reviews and ratings from users and critics, and some frequently asked questions. By the end of this article, you will be ready to download DOP 2 and have fun with this amazing brain game.

    -

    How to Play DOP 2

    -

    The gameplay of DOP 2 is very straightforward and intuitive. All you have to do is touch the screen and drag your finger to erase part of the drawing and reveal what's behind it. The game will give you a hint or a question to guide you in finding the correct part to erase. For example, it may ask you to "find the thief" or "make him happy". You have to use your logic and imagination to figure out what the drawing is hiding.

    -

    The game has hundreds of levels with different themes and difficulties. Some levels are easy and obvious, while others are more challenging and require more thinking. You will encounter various scenarios, such as crime scenes, romantic situations, funny jokes, historical events, artistic creations, and more. Each level has a unique story and a surprising twist that will make you laugh or gasp.

    -

    The game does not have a time limit or a scoring system, so you can play at your own pace and enjoy the process. There is also no way to fail or lose in this game. If you erase the wrong part, the drawing will just reset and you can try again. The game is designed to make you think, not make you cry.

    -

    dop 2 delete one part game
    -dop 2 game download
    -dop 2 game online
    -dop 2 game walkthrough
    -dop 2 game play store
    -dop 2 game app
    -dop 2 game cheats
    -dop 2 game answers
    -dop 2 game levels
    -dop 2 game hints
    -dop 2 game review
    -dop 2 game trailer
    -dop 2 game apk
    -dop 2 game mod
    -dop 2 game ios
    -dop 2 game for pc
    -dop 2 game free
    -dop 2 game unblocked
    -dop 2 game yandex
    -dop 2 game icon games
    -dop 2 delete one part puzzles
    -dop 2 delete one part solutions
    -dop 2 delete one part tips
    -dop 2 delete one part tricks
    -dop 2 delete one part funny
    -dop 2 delete one part logic
    -dop 2 delete one part brain teasers
    -dop 2 delete one part riddles
    -dop 2 delete one part challenges
    -dop 2 delete one part questions
    -dop 2 delete one part youtube
    -dop 2 delete one part reddit
    -dop 2 delete one part facebook
    -dop 2 delete one part instagram
    -dop 2 delete one part twitter
    -dop 2 delete one part tiktok
    -dop 2 delete one part new scientist
    -dop 2 delete one part the sun
    -dop 2 delete one part yahoo news
    -dop 2 delete one part wikipedia

    -

    Tips and Tricks for Solving the Puzzles

    -

    While playing DOP 2, you may encounter some puzzles that seem impossible or confusing. Don't worry, we have some tips and tricks for you to help you solve them.

    -
      -
    • Pay attention to the hint or question that the game gives you. It will often point you in the right direction or give you a clue about what to look for.
    • -
    • Use your eraser as a magnifying glass. Sometimes, erasing a small part of the drawing can reveal something that you may have missed or overlooked.
    • -
    • Think outside the box. Sometimes, the solution is not obvious or literal. You may have to erase something that seems unrelated or irrelevant to the hint or question. For example, if the game asks you to "make him happy", you may have to erase his frown or his tears, not his clothes or his hair.
    • -
    • Have fun and experiment. There is no penalty for erasing the wrong part, so feel free to try different things and see what happens. You may discover something unexpected or hilarious.
    • -
    -

    Benefits of Playing DOP 2

    -

    DOP 2 is not only a fun and entertaining game, but also a beneficial one. Playing this game can help you improve your reasoning skills and creativity in various ways.

    -
      -
    • It can enhance your logical thinking and problem-solving abilities. The game challenges you to find the hidden meaning behind the drawings and to apply your knowledge and common sense to solve the puzzles.
    • -
    • It can stimulate your imagination and curiosity. The game encourages you to explore different possibilities and scenarios and to look at things from different perspectives.
    • -
    • It can boost your memory and concentration. The game requires you to pay attention to details and to remember what you have erased and what you have not.
    • -
    • It can reduce your stress and boredom. The game offers you a relaxing and enjoyable way to pass the time and to distract yourself from your worries and troubles.
    • -
    -

    Features of DOP 2

    -

    DOP 2 is a well-designed and well-developed game that has many features that make it appealing and attractive to players of all ages and backgrounds.

    -

    Graphics and Sound

    -

    The game has a cartoon style and cute animations that suit the humorous and playful tone of the game. The drawings are colorful and vivid, and the erasing effect is smooth and satisfying. The game also has optional music, sound effects, and vibration that add to the fun and excitement of the game. You can adjust these settings according to your preference.

    -

    Settings and Controls

    -

    The game has simple and easy controls that anyone can master. You just need one finger to swipe across the screen to erase parts of the drawing. You can also zoom in or out by pinching the screen with two fingers. The game has a pause button that allows you to stop the game at any time. You can also access the settings menu from there, where you can turn on or off the music, sound effects, vibration, notifications, and more.

    -

    Compatibility and Availability

    -

    The game is compatible with Android and iOS devices, so you can play it on your smartphone or tablet. The game is free to download and play, but it contains ads that may interrupt your gameplay. You can remove the ads by purchasing the premium version of the game for a small fee. The game also has in-app purchases that allow you to buy hints or skip levels if you get stuck.

    -

    Reviews and Ratings of DOP 2

    -

    DOP 2 has received positive feedback from users and critics alike, who praise its originality, creativity, humor, difficulty, variety, quality, and more. The game has an average rating of 4.5 out of 5 stars on Google Play and 4.6 out of 5 stars on App Store , with over 10 million downloads on each platform.

    -

    What Users Say About DOP 2

    -

    Here are some quotes from user reviews on Google Play and App Store :

    -
    "This game is awesome! It makes you think outside the box and it's very entertaining. I love how each level has a different theme and a different story. It's like watching a mini movie."
    -
    "This game is so fun and addictive! I can't stop playing it. It's challenging but not frustrating. It's funny but not silly. It's perfect for killing time or relaxing."
    -
    "This game is amazing! It's very creative and original. I like how it tests your logic and imagination. It also makes me laugh a lot with its jokes and surprises."
    -

    What Critics Say About DOP 2

    -

    Here are some quotes from professional reviews on websites and blogs:

    -
    "DOP 2: Delete One Part is a clever brain teaser that will keep you hooked for hours. The game combines logic puzzles with hidden object games in a unique way that will challenge your mind and tickle your funny bone." -
    "DOP 2: Delete One Part is a clever brain teaser that will keep you hooked for hours. The game combines logic puzzles with hidden object games in a unique way that will challenge your mind and tickle your funny bone." - [AppAdvice](^1^)
    -
    "DOP 2: Delete One Part is a fun and addictive game that will make you think outside the box. The game has hundreds of levels with different themes and difficulties, and each one has a surprising twist that will make you laugh or gasp. The game is also easy to play and has cute graphics and sound effects." - [JustUseApp](^3^)
    -

    Conclusion

    -

    DOP 2: Delete One Part is a game that you don't want to miss if you love brain games. It is a game that will make you think, laugh, and have fun at the same time. It is a game that will improve your reasoning skills and creativity. It is a game that has many features and benefits that make it worth playing. It is a game that has received rave reviews and ratings from users and critics alike.

    -

    So what are you waiting for? Download DOP 2: Delete One Part now and enjoy this amazing brain game. You won't regret it!

    -

    FAQs

    -

    Here are some frequently asked questions about DOP 2: Delete One Part with answers.

    -
      -
    1. Q: How many levels are there in DOP 2?
      A: There are over 300 levels in DOP 2, and more are added regularly.
    2. -
    3. Q: How can I get more hints or skip levels in DOP 2?
      A: You can get more hints or skip levels by watching ads or by making in-app purchases.
    4. -
    5. Q: How can I contact the developer of DOP 2?
      A: You can contact the developer of DOP 2 by emailing them at support@saygames.by or by visiting their website at [https://say.games](^5^).
    6. -
    7. Q: Is DOP 2 suitable for children?
      A: DOP 2 is rated Teen on Google Play and 12+ on App Store, so it may contain some content that is not appropriate for younger children. Parental discretion is advised.
    8. -
    9. Q: Is DOP 2 available offline?
      A: Yes, you can play DOP 2 offline, but you will need an internet connection to watch ads or make in-app purchases.
    10. -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Format Factory 2.60 for Windows 7 and Enjoy a Free Comprehensive and Easy-to-Use File Converter.md b/spaces/fatiXbelha/sd/Download Format Factory 2.60 for Windows 7 and Enjoy a Free Comprehensive and Easy-to-Use File Converter.md deleted file mode 100644 index 05435a382636fedfc55bfc61fe254dc719308189..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Format Factory 2.60 for Windows 7 and Enjoy a Free Comprehensive and Easy-to-Use File Converter.md +++ /dev/null @@ -1,223 +0,0 @@ -
    -

    Format Factory 2.60: A Free and Versatile Multimedia Converter for Windows 7

    -

    If you are looking for a free, comprehensive, and easy-to-use multimedia converter for your Windows 7 computer, you might want to check out Format Factory 2.60. This software can help you convert almost any file format to another with just a few clicks. Whether you want to change the format of your videos, audios, images, or documents, Format Factory 2.60 can handle it all.

    -

    format factory 2.60 free download for windows 7


    DOWNLOADhttps://urllie.com/2uNAb4



    -

    In this article, we will give you a detailed guide on how to download, install, and use Format Factory 2.60 on your Windows 7 PC. We will also review its features, benefits, drawbacks, and alternatives. By the end of this article, you will have a clear idea of whether Format Factory 2.60 is the right choice for you or not.

    -

    What is Format Factory 2.60?

    -

    Format Factory 2.60 is a multifunctional media converter software developed by Free Time. It was released in December 2010 and has been updated regularly since then. The latest version is 5.8.0 as of March 2021.

    -

    A brief introduction to the software and its main features

    -

    Format Factory 2.60 is designed to help users convert various types of media files from one format to another without losing quality or compatibility. It also offers some additional tools for ripping discs, mixing files, repairing files, and more.

    -

    Some of the main features of Format Factory 2.60 are:

    -
      -
    • It supports hardware acceleration for faster conversion speed.
    • -
    • It allows batch processing of multiple files at once.
    • -
    • It offers disc-ripping options for CDs, DVDs, and Blu-rays.
    • -
    • It allows file mixing and joining utilities for video and audio files.
    • -
    • It features a built-in screen recorder and video downloader.
    • -
    • It features a watermark or logo remover.
    • -
    • It supports multi-language up to 62 languages.
    • -
    -

    The supported input and output formats for video, audio, image, and document files

    -

    Format Factory 2.60 supports a wide range of input and output formats for different types of media files. Here is a table that shows some of the most common formats supported by the software:

    - - - - - - - - - - - - - - - - - - - - - - - - - - -
    File TypeInput FormatsOutput Formats
    VideoMP4, AVI, 3GP, RMVB, MKV, MOV, FLV, SWF, MPEG, VOB, WMV, etc.MP4, AVI, 3GP, RMVB, MKV, MOV, FLV, SWF, MPEG, VOB, WMV, etc.
    AudioMP3, WMA, AAC, OGG, FLAC, WAV, AMR, M4A, etc.MP3, WMA, AAC, OGG, FLAC, WAV, AMR, M4A, etc.
    ImageJPG, PNG, BMP, GIF, TIF, ICO, PCX, TGA, etc.JPG, PNG, BMP, GIF, TIF, ICO, PCX, TGA, etc.
    DocumentPDF, DOCX/DOC/RTF/TXT/ODT/WPD/HTML/XML/XLSX/XLS/ODS/PPTX/PPT/ODP/CBR/CBZ/DJVU/EPUB/MOBI/AZW3/FB2/LIT/LRF/PDB/TXTZ/SNB/TCR/ZNO etc.PDF/DOCX/DOC/RTF/TXT/ODT/WPD/HTML/XML/XLSX/XLS/ODS/PPTX/PPT/ODP/CBR/CBZ/DJVU/EPUB/MOBI/AZW3/FB2/LIT/LRF/PDB/TXTZ/SNB/TCR/ZNO etc.
    -

    You can also customize the output format by changing the parameters such as resolution, bitrate, frame rate, sample rate, channels, quality, etc.

    -

    format factory 2.60 windows 7 download free
    -how to download format factory 2.60 for windows 7
    -format factory 2.60 free software for windows 7
    -format factory 2.60 windows 7 compatible free download
    -download format factory 2.60 free full version for windows 7
    -format factory 2.60 free converter for windows 7
    -format factory 2.60 windows 7 installation guide free
    -format factory 2.60 free multimedia tool for windows 7
    -format factory 2.60 windows 7 offline installer free download
    -download format factory 2.60 free latest version for windows 7
    -format factory 2.60 free video converter for windows 7
    -format factory 2.60 windows 7 system requirements free
    -format factory 2.60 free audio converter for windows 7
    -format factory 2.60 windows 7 review and rating free
    -format factory 2.60 free image converter for windows 7
    -format factory 2.60 windows 7 features and benefits free
    -format factory 2.60 free text converter for windows 7
    -format factory 2.60 windows 7 support and help free
    -format factory 2.60 free file size reducer for windows 7
    -format factory 2.60 windows 7 alternatives and comparisons free
    -format factory 2.60 free batch conversion for windows 7
    -format factory 2.60 windows 7 license and terms free
    -format factory 2.60 free quality and performance for windows 7
    -format factory 2.60 windows 7 tips and tricks free
    -format factory 2.60 free customization and settings for windows 7
    -format factory 2.60 windows 7 feedback and suggestions free
    -format factory 2.60 free update and upgrade for windows 7
    -format factory 2.60 windows 7 troubleshooting and errors free
    -format factory 2.60 free security and privacy for windows 7
    -format factory 2.60 windows 7 testimonials and reviews free
    -format factory 2.60 free compatibility and integration for windows 7
    -format factory 2.60 windows 7 pros and cons free
    -format factory 2.60 free speed and efficiency for windows 7
    -format factory 2.60 windows 7 tutorials and guides free
    -format factory 2.60 free formats and extensions for windows 7
    -format factory 2.60 windows 7 FAQs and answers free
    -format factory 2.60 free languages and translations for windows

    -

    How to Download and Install Format Factory 2.60 for Windows 7?

    -

    To download and install Format Factory 2.60 for Windows 7, you need to follow these steps:

    -

    The steps to download the software from the official website or a trusted source

    -
      -
    • Go to the official website of Format Factory at http://www.pcfreetime.com/formatfactory/index.php?language=en.
    • -
    • Click on the "Download" button on the top right corner of the page.
    • -
    • Select the version you want to download. The latest version is 5.8.0 as of March 2021. You can also choose an older version such as 2.60 if you prefer.
    • -
    • Choose a download mirror from the list. You can also use a third-party download manager to speed up the process.
    • -
    • Save the file to your computer. The file size is about 100 MB.
    • -
    -

    The steps to install the software and avoid unwanted programs or extensions

    -
      -
    • Double-click on the downloaded file to launch the installer.
    • -
    • Select your preferred language and click "OK".
    • -
    • Read and accept the license agreement and click "Next".
    • -
    • Choose a destination folder for the installation and click "Next".
    • -
    • Deselect any unwanted programs or extensions that may be offered along with the software. For example, you may want to uncheck "Install Format Factory Toolbar" or "Set Bing as my default search engine". Click "Next".
    • -
    • Click "Install" to start the installation process. It may take a few minutes depending on your system configuration.
    • -
    • Click "Finish" to complete the installation and launch the software.
    • -
    -

    How to Use Format Factory 2.60 to Convert Files on Windows 7?

    -

    To use Format Factory 2.60 to convert files on Windows 7, you need to follow these steps:

    -

    The steps to select the output format and add files for conversion

    -
      -
    • Open Format Factory 2.60 on your computer.
    • -
    • Select the output format you want from the left panel. For example, if you want to convert a video file to MP4 format, click on "Video" and then "All to MP4". You can also choose other formats such as AVI, MKV, MOV, FLV, etc.
    • -
    • Click on "Add File" to browse and select the file(s) you want to convert. You can also drag and drop the file(s) to the interface.
    • -
    • You can see the file name, size, duration, and resolution of the selected file(s) in the list. You can also remove or clear the file(s) if you want.
    • -
    -

    The steps to adjust the output settings and start the conversion process

    -
      -
    • Click on "Output Setting" to customize the output parameters such as resolution, bitrate, frame rate, sample rate, channels, quality, etc. You can also choose a preset profile for different devices such as iPhone, iPad, Android, PSP, etc.
    • -
    • Click on "Option" to change the output folder, language, theme, hardware acceleration, etc. You can also check or uncheck some options such as "Shut down computer when conversion completed", "Delete source file after conversion", etc.
    • -
    • Click on "Start" to begin the conversion process. You can see the progress bar, time remaining, and status of each file in the list. You can also pause or stop the conversion at any time.
    • -
    • When the conversion is done, you can find the output file(s) in the output folder or click on "Open Output Folder" to open it directly.
    • -
    -

    The steps to use the disc-ripping, file-mixing, file-repairing, and other tools

    -
      -
    • To rip a CD, DVD, or Blu-ray disc to a digital format, click on "ROM Device\DVD\CD\ISO" and then choose the disc type and output format. Insert the disc into your drive and click on "Add File" to select the tracks or chapters you want to rip. Click on "Start" to begin the ripping process.
    • -
    • To mix two or more video or audio files into one file, click on "Utilities" and then choose "Video Joiner" or "Audio Joiner". Click on "Add File" to select the files you want to mix. You can also adjust the order and output settings of the files. Click on "Start" to begin the mixing process.
    • -
    • To repair a damaged video or audio file, click on "Utilities" and then choose "Video Fixer" or "Audio Fixer". Click on "Add File" to select the file you want to repair. Click on "Start" to begin the repairing process.
    • -
    • To use other tools such as screen recorder, video downloader, watermark remover, etc., click on "Utilities" and then choose the tool you want. Follow the instructions on the screen to use the tool.
    • -
    -

    What are the Benefits and Drawbacks of Format Factory 2.60?

    -

    Format Factory 2.60 is a powerful and versatile multimedia converter software that can meet most of your conversion needs. However, it also has some limitations and drawbacks that you should be aware of before using it. Here are some of the pros and cons of Format Factory 2.60:

    -

    The advantages of using the software, such as fast speed, hardware acceleration, batch processing, etc.

    -
      -
    • It is free to use and does not require registration or subscription.
    • -
    • It supports a wide range of input and output formats for different types of media files.
    • -
    • It offers hardware acceleration for faster conversion speed and better performance.
    • -
    • It allows batch processing of multiple files at once with one click.
    • -
    • It offers disc-ripping options for CDs, DVDs, and Blu-rays.
    • -
    • It allows file mixing and joining utilities for video and audio files.
    • -
    • It features a built-in screen recorder and video downloader.
    • -
    • It features a watermark or logo remover.
    • -
    • It supports multi-language up to 62 languages.
    • -
    -

    The disadvantages of using the software, such as limited containers, outdated interface, etc.

    -
      -
    • It does not support some popular container formats such as MKV, M4V, M2TS, etc.
    • -
    • It has an outdated interface that may not be user-friendly or intuitive for some users.
    • -
    • It may install some unwanted programs or extensions along with the software if you are not careful during the installation process.
    • -
    • It may contain some bugs or errors that may cause crashes or failures during the conversion process.
    • -
    • It may not be compatible with some newer versions of Windows such as Windows 10 or 11.
    • -
    -

    What are the Best Alternatives to Format Factory 2.60?

    If you are not satisfied with Format Factory 2.60 or want to try some other multimedia converter software, you can check out some of the best alternatives to Format Factory 2.60. Here are some of them:

    -

    A brief comparison of some popular alternatives, such as HandBrake, FFmpeg, XMedia Recode, etc.

    - - - - - - - - - - - - - - - - - - - - - - - - -
    SoftwareFeaturesProsCons
    HandBrakeA free and open-source video converter and transcoder that supports various formats and devices.- It has a simple and modern interface.
    - It offers advanced options for video encoding and filtering.
    - It supports subtitles, chapters, and metadata.
    - It does not support audio or image conversion.
    - It may not support some rare or proprietary formats.
    - It may have some compatibility issues with Windows 7.
    FFmpegA free and open-source command-line tool that can convert, stream, record, and edit various types of media files.- It is very powerful and flexible.
    - It supports almost any format and codec.
    - It offers many features and functions for media processing.
    - It has a steep learning curve.
    - It does not have a graphical user interface.
    - It may require some additional libraries or dependencies.
    XMedia RecodeA free and lightweight video converter and editor that supports various formats and devices.- It has a user-friendly and customizable interface.
    - It offers batch processing and hardware acceleration.
    - It allows basic editing and trimming of video files.
    - It does not support audio or image conversion.
    - It may not support some newer formats or codecs.
    - It may have some stability or performance issues.
    -

    A recommendation of the best alternative based on features, performance, and user reviews

    -

    Based on our comparison, we recommend HandBrake as the best alternative to Format Factory 2.60. HandBrake is a popular and reliable video converter software that can handle most of your conversion needs. It has a simple and modern interface that is easy to use. It also offers advanced options for video encoding and filtering that can improve the quality and efficiency of your output files. It supports subtitles, chapters, and metadata that can enhance your viewing experience. HandBrake is also free and open-source, which means you can use it without any limitations or costs.

    -

    However, if you need to convert audio or image files, or if you prefer a command-line tool or a lightweight software, you can also try FFmpeg or XMedia Recode. They are also good alternatives to Format Factory 2.60 that can offer different features and functions for your media conversion needs.

    -

    Conclusion

    -

    In conclusion, Format Factory 2.60 is a free and versatile multimedia converter software that can help you convert almost any file format to another with just a few clicks. It also offers some additional tools for ripping discs, mixing files, repairing files, and more. However, it also has some limitations and drawbacks that you should be aware of before using it. If you are looking for a better alternative to Format Factory 2.60, we recommend HandBrake as the best option based on features, performance, and user reviews.

    -

    We hope this article has given you a detailed guide on how to download, install, and use Format Factory 2.60 on your Windows 7 PC. We also hope you have learned about its features, benefits, drawbacks, and alternatives. If you have any questions or feedback about Format Factory 2.60 or this article, please feel free to leave a comment below. Thank you for reading!

    -

    FAQs

    -

    Q1: Is Format Factory 2.60 safe to use?

    -

    A1: Format Factory 2.60 is generally safe to use as long as you download it from the official website or a trusted source. However, you should be careful during the installation process as it may offer some unwanted programs or extensions that may harm your computer or browser. You should also scan the downloaded file with an antivirus software before running it.

    -

    Q2: How to update Format Factory 2.60 to the latest version?

    -

    A2: To update Format Factory 2.60 to the latest version, you can follow these steps:

    -
      -
    • Open Format Factory 2.60 on your computer.
    • -
    • Click on "Help" on the top menu bar and then click on "Check Update".
    • -
    • If there is a new version available, you will see a pop-up window that shows the version number and the download link.
    • -
    • Click on the download link and save the file to your computer.
    • -
    • Run the downloaded file and follow the instructions to install the new version.
    • -
    • Restart Format Factory 2.60 to enjoy the new features and improvements.
    • -
    -

    Q3: How to uninstall Format Factory 2.60 from Windows 7?

    -

    A3: To uninstall Format Factory 2.60 from Windows 7, you can follow these steps:

    -
      -
    • Close Format Factory 2.60 if it is running on your computer.
    • -
    • Click on the "Start" button and then click on "Control Panel".
    • -
    • Click on "Programs" and then click on "Uninstall a program".
    • -
    • Find and select "Format Factory" from the list of programs and click on "Uninstall".
    • -
    • Follow the instructions to complete the uninstallation process.
    • -
    • Delete any leftover files or folders related to Format Factory 2.60 from your computer.
    • -
    -

    Q4: How to contact Format Factory support team?

    -

    A4: To contact Format Factory support team, you can use one of these methods:

    - -

    Q5: How to donate to Format Factory developers?

    -

    A5: To donate to Format Factory developers, you can use one of these methods:

    -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Hello Neighbor (MOD Unlocked) 2.3.8 for Android - Stealth Horror Game.md b/spaces/fatiXbelha/sd/Download Hello Neighbor (MOD Unlocked) 2.3.8 for Android - Stealth Horror Game.md deleted file mode 100644 index 88b79f5006a3afbd9788e626926f9d5ad0c776bd..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Hello Neighbor (MOD Unlocked) 2.3.8 for Android - Stealth Horror Game.md +++ /dev/null @@ -1,134 +0,0 @@ -
    -

    Download Game Hello Neighbor Mod APK: A Stealth Horror Game with Unlimited Features

    -

    If you are looking for a thrilling and challenging game that will keep you on the edge of your seat, you might want to try Hello Neighbor. This is a stealth horror game that requires you to sneak into your neighbor's house and discover his dark secrets. But be careful, because he is not an easy opponent. He has an advanced artificial intelligence that learns from your every move and sets traps to stop you. To make things more interesting, you can download the mod apk version of Hello Neighbor, which gives you access to unlimited features and enhancements. In this article, we will tell you everything you need to know about Hello Neighbor and how to download game hello neighbor mod apk.

    -

    download game hello neighbor mod apk


    Download File >>> https://urllie.com/2uNzY3



    -

    What is Hello Neighbor?

    -

    A brief introduction to the game and its genre

    -

    Hello Neighbor is a game developed by Dynamic Pixels and published by tinyBuild. It was released in 2017 for Windows, Xbox One, PlayStation 4, Nintendo Switch, iOS, and Android devices. It belongs to the genre of stealth horror, which combines elements of stealth, puzzle-solving, exploration, and survival. The game has a cartoonish style and a colorful graphics, but it also has a dark and creepy atmosphere that creates a contrast between the appearance and the reality.

    -

    The main features and gameplay of Hello Neighbor

    -

    The game revolves around the protagonist, who is a curious child who moves into a new neighborhood. He notices that his neighbor across the street has a mysterious basement that seems to hide something sinister. He decides to investigate and find out what is going on, but he has to avoid being caught by the neighbor, who will chase him down and throw him out if he sees him. The game has three acts, each with a different setting and objective. The player has to use various objects and tools to distract, evade, or fight the neighbor, as well as to solve puzzles and unlock doors. The game also has a sandbox mode, where the player can explore the neighbor's house freely without any restrictions.

    -

    The challenges and rewards of Hello Neighbor

    -

    One of the most appealing aspects of Hello Neighbor is its dynamic and adaptive gameplay. The neighbor is not a scripted enemy that follows a fixed pattern. He is an intelligent and unpredictable foe that reacts to the player's actions and learns from them. He will set up cameras, bear traps, alarms, mannequins, and other obstacles to prevent the player from entering his house or reaching his basement. He will also memorize the player's habits and preferences, such as which window he likes to climb through or which room he likes to hide in. He will also use shortcuts and secret passages to catch up with the player or surprise him from behind. This makes the game more challenging and exciting, as the player has to constantly change his strategy and improvise new solutions. On the other hand, the game also rewards the player for his creativity and curiosity. The player can discover hidden secrets, easter eggs, references, clues, and backstory elements that enrich the game's world and story. The player can also unlock new items, abilities, modes, and endings depending on his choices and actions.

    -

    What is a mod apk?

    -

    The definition and benefits of a mod apk

    -

    A mod apk is a modified version of an original application file (apk) that has been altered or enhanced by third-party developers or users. A mod apk can offer various benefits that are not available in the original version, such as unlimited resources, features, functions, graphics, performance, or compatibility. A mod apk can also remove unwanted ads, permissions, restrictions, or bugs that may affect the user's experience. A mod apk can be useful for users who want to enjoy a game or an app to the fullest, or who want to try something new and different.

    -

    The risks and precautions of a mod apk

    -

    However, a mod apk also comes with some risks and drawbacks that the user should be aware of. A mod apk is not an official or authorized version of the original app, and it may not be compatible with the latest updates or patches. A mod apk may also contain viruses, malware, spyware, or other harmful software that can damage the user's device or compromise his privacy and security. A mod apk may also violate the terms and conditions of the original app, and the user may face legal consequences or penalties for using it. Therefore, the user should be careful and cautious when downloading and installing a mod apk. He should only use trusted and reliable sources and websites, and he should scan the file for any potential threats before opening it. He should also backup his data and create a restore point in case something goes wrong. He should also respect the rights and interests of the original developers and creators, and he should not use the mod apk for any illegal or unethical purposes.

    -

    download hello neighbor mod apk unlocked
    -download hello neighbor mod apk latest version
    -download hello neighbor mod apk android
    -download hello neighbor mod apk happymod
    -download hello neighbor mod apk for pc
    -download game hello neighbor mod apk offline
    -download game hello neighbor mod apk free
    -download game hello neighbor mod apk full version
    -download game hello neighbor mod apk no obb
    -download game hello neighbor mod apk unlimited money
    -download hello neighbor mod menu apk
    -download hello neighbor mod ghost mode apk
    -download hello neighbor mod invisible apk
    -download hello neighbor mod granny apk
    -download hello neighbor mod among us apk
    -how to download hello neighbor mod apk
    -where to download hello neighbor mod apk
    -best site to download hello neighbor mod apk
    -safe download hello neighbor mod apk
    -easy download hello neighbor mod apk
    -download game hello neighbor hide and seek mod apk
    -download game hello neighbor act 1 mod apk
    -download game hello neighbor act 2 mod apk
    -download game hello neighbor act 3 mod apk
    -download game hello neighbor act 4 mod apk
    -download game hello neighbor alpha 4 mod apk
    -download game hello neighbor alpha 3 mod apk
    -download game hello neighbor alpha 2 mod apk
    -download game hello neighbor alpha 1 mod apk
    -download game hello neighbor beta 3 mod apk
    -download game hello neighbor beta 2 mod apk
    -download game hello neighbor beta 1 mod apk
    -download game hello neighbor final release mod apk
    -download game hello neighbor secret ending mod apk
    -download game hello neighbor multiplayer mod apk
    -download game hello neighbor online mod apk
    -download game hello neighbor horror mod apk
    -download game hello neighbor funny moments mod apk
    -download game hello neighbor all acts unlocked mod apk
    -download game hello neighbor all levels unlocked mod apk
    -download game hello neighbour hack mod apk
    -download game helloneighbor cheat mod apk
    -download game helloneighbor walkthrough guide mod apk
    -download game helloneighbor tips and tricks mod apk
    -download game helloneighbor gameplay review mod apk
    -download game helloneighbor graphics settings mod apk
    -download game helloneighbor sound effects mod apk
    -download game helloneighbor custom maps mod apk

    -

    The best sources and websites for downloading mod apks

    -

    There are many sources and websites that offer mod apks for various games and apps, but not all of them are safe and trustworthy. Some of them may contain fake or malicious files that can harm the user's device or data. Some of them may also have annoying ads, pop-ups, redirects, or surveys that can ruin the user's experience. Therefore, the user should do some research and check some reviews before downloading any mod apk from any source or website. Here are some of the best sources and websites for downloading mod apks that we recommend:

    -
      -
    • HappyMod: This is one of the most popular and reputable sources for mod apks. It has a large collection of mod apks for various games and apps, covering different categories and genres. It also has a user-friendly interface and a fast download speed. It also has a community of users who rate and review the mod apks, so the user can easily find the best and most suitable ones for his needs.
    • -
    • APKPure: This is another well-known and reliable source for mod apks. It has a huge database of mod apks for different games and apps, as well as original apks that are not available on Google Play Store. It also has a simple and elegant design and a smooth download process. It also has a team of editors who verify and test the mod apks, so the user can be assured of their quality and safety.
    • -
    • ModDroid: This is a newer but promising source for mod apks. It has a decent selection of mod apks for various games and apps, especially for Android devices. It also has a modern and attractive interface and a fast download speed. It also has a blog section where the user can find useful tips, guides, news, and reviews about mod apks.
    • -
    -

    How to download game hello neighbor mod apk?

    -

    The steps and requirements for downloading and installing the mod apk

    -

    Now that you know what Hello Neighbor is and what a mod apk is, you might be wondering how to download game hello neighbor mod apk. The process is not very complicated, but it does require some steps and requirements that you should follow carefully. Here are the steps and requirements for downloading and installing the mod apk:

    -
      -
    1. First, you need to have an Android device that meets the minimum system requirements for running Hello Neighbor. According to Google Play Store, these are: Android 7.0 or higher, 1 GB of RAM or more, 1 GB of free storage space or more, OpenGL ES 3.0 support or higher.
    2. -
    3. Second, you need to enable the installation of apps from unknown sources on your device. This is because the mod apk is not from Google Play Store, so you need to allow your device to install it from other sources. To do this, you need to go to Settings > Security > Unknown Sources (or Settings > Apps > Special Access > Install Unknown Apps) and toggle it on.
    4. -
    5. Third, you need to download game hello neighbor mod apk from one of the sources or websites that we mentioned above (HappyMod, APKPure, ModDroid). You can use your browser or a download manager app to do this. You need to find the mod apk file that matches your device's specifications and preferences, and then click on the download button or link. You may need to wait for a few seconds or minutes for the download to complete, depending on your internet speed and the file size.
    6. -
    7. Fourth, you need to locate the downloaded mod apk file on your device's storage. You can use a file manager app or your device's default file explorer to do this. You need to find the folder where you saved the mod apk file, which is usually the Downloads folder or the folder of the app that you used to download it.
    8. -
    9. Fifth, you need to tap on the mod apk file and install it on your device. You may need to grant some permissions or accept some terms and conditions before proceeding with the installation. You may also see a warning message that says "This type of file can harm your device. Do you want to keep it anyway?". You can ignore this message and tap on OK or Yes, as long as you trust the source or website that you downloaded it from.
    10. -
    11. Sixth, you need to wait for the installation to finish, which may take a few seconds or minutes, depending on your device's performance and the mod apk's features. You may see a progress bar or a notification that shows the installation status.
    12. -
    13. Seventh, you need to open the mod apk app and enjoy playing Hello Neighbor with unlimited features and enhancements. You can find the app icon on your device's home screen or app drawer. You can also check if the mod apk is working properly by looking for any changes or additions in the game's interface, settings, or gameplay.
    14. -
    -

    The advantages and disadvantages of the mod apk version of Hello Neighbor

    -

    Downloading and installing the mod apk version of Hello Neighbor can have some advantages and disadvantages that you should consider before doing so. Here are some of them:

    - - - - - - - - - - - - - - - - - - - - - -
    AdvantagesDisadvantages
    - You can access unlimited resources, such as coins, keys, items, tools, weapons, etc., that can help you in your mission.- You may encounter some bugs, glitches, errors, crashes, or compatibility issues that can affect your game's performance or functionality.
    - You can unlock new features, such as modes, levels, characters, skins, costumes, etc., that can enhance your game's variety and fun.- You may lose some features, such as achievements, leaderboards, online multiplayer, etc., that can reduce your game's challenge and social interaction.
    - You can customize your game's settings, such as graphics, sound, controls, difficulty, etc., that can improve your game's quality and comfort.- You may violate your game's terms and conditions, and you may face some legal consequences or penalties for using an unauthorized version of the game.
    - You can experiment with different options and possibilities that can increase your game's creativity and curiosity.- You may lose some of the original game's charm and appeal, and you may miss out on some of the intended game's experience and story.
    -

    The tips and tricks for playing the mod apk version of Hello Neighbor

    -

    If you decide to download game hello neighbor mod apk and play it on your device, here are some tips and tricks that can help you make the most out of it:

    -
      -
    • - Use your resources wisely. Even though you have unlimited resources in the mod apk version of Hello Neighbor, you should not waste them or use them unnecessarily. You should still plan your strategy and use your resources when you really need them or when they can give you an advantage.
    • -
    • - Explore your surroundings. The mod apk version of Hello Neighbor may have some hidden secrets or surprises that are not present in the original version. You should explore every corner and every room of the neighbor's house and look for any clues or easter eggs that can reveal more about the game's world and story.
    • -
    • - Try different modes. The mod apk version of Hello Neighbor may have some new modes that are not available in the original version. You should try different modes and see how they change or affect your game's gameplay and difficulty. For example, you may find a mode that lets you play as the neighbor or a mode that lets you play with other players online.
    • -
    • - Have fun. The most important tip for playing the mod apk version of Hello Neighbor is to have fun. You should enjoy playing the game and appreciate its features and enhancements. You should also respect the original developers and creators of Hello Neighbor and support their work if you like their game.
    • -
    -

    Conclusion

    -

    A summary of the main points and a call to action

    -

    In conclusion, Hello Neighbor is a stealth horror game that challenges you to sneak into your neighbor's house and uncover his secrets. It is a game that combines stealth, puzzle-solving, exploration, and survival, with a dynamic and adaptive gameplay that changes according to your actions. You can download game hello neighbor mod apk to enjoy unlimited features and enhancements that can make your game more fun and interesting. However, you should also be aware of the risks and drawbacks of using a mod apk, and you should only download it from trusted and reliable sources. You should also follow the steps and requirements for downloading and installing the mod apk, and you should use some tips and tricks for playing it. If you are ready to face your neighbor and discover his secrets, download game hello neighbor mod apk now and start playing!

    -

    FAQs

    -

    Here are some frequently asked questions about Hello Neighbor and the mod apk version:

    -
      -
    1. Is Hello Neighbor free to play?
    2. -

      No, Hello Neighbor is not free to play. You need to purchase the game from the official platforms or stores, such as Steam, Microsoft Store, PlayStation Store, Nintendo eShop, App Store, or Google Play Store. The price may vary depending on your region and device.

      -
    3. Is Hello Neighbor suitable for children?
    4. -

      Yes and no. Hello Neighbor is rated E10+ by ESRB, which means it is suitable for everyone 10 years and older. However, the game may contain some scenes or elements that may be scary or disturbing for some children, such as violence, blood, gore, jump scares, or dark themes. Therefore, parental guidance and discretion are advised.

      -
    5. Is the mod apk version of Hello Neighbor safe to use?
    6. -

      It depends. The mod apk version of Hello Neighbor can be safe to use if you download it from a trusted and reliable source or website, and if you scan it for any viruses or malware before installing it. However, the mod apk version of Hello Neighbor can also be unsafe to use if you download it from an unknown or suspicious source or website, or if you install it without checking it for any threats. Therefore, you should be careful and cautious when downloading and installing the mod apk version of Hello Neighbor.

      -
    7. Can I play Hello Neighbor online with other players?
    8. -

      Yes, you can. Hello Neighbor has an online multiplayer mode called Secret Neighbor, which is a spin-off game that allows you to play with up to six players online. In this mode, one of the players is secretly the neighbor in disguise, who can use his abilities to sabotage the others. The other players have to work together to find the keys and escape the house before the neighbor catches them.

      -
    9. Can I play Hello Neighbor offline without internet connection?
    10. -

      Yes, you can. Hello Neighbor does not require an internet connection to play the single-player mode or the sandbox mode. You can play these modes offline without any problem. However, you need an internet connection to play the online multiplayer mode or to access some features or updates that may require online verification.

      -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/fatmacankara/ASCARIS/code/alphafold_model.py b/spaces/fatmacankara/ASCARIS/code/alphafold_model.py deleted file mode 100644 index fd8b7a5f3d1e2123ae4d4d9cf686c0be03a37fff..0000000000000000000000000000000000000000 --- a/spaces/fatmacankara/ASCARIS/code/alphafold_model.py +++ /dev/null @@ -1,36 +0,0 @@ -from collections import Counter -import glob -def reduce_model_dict(dict): - for key, val in dict.items(): - used = [] - for key2, val2 in val.items(): - new = [] - for i in val2: - if i not in used: - new.append(i) - used.append(i) - val[key2] = new - return dict - - -def which_model(position): - models_dict = {} - x = 1 - for i, j in zip(range(1400, 27000, 200), range(1, 27000, 200)): - if position <= i and position >= j: - models_dict[x] = position - x += 1 - return models_dict - -def modelCount(path_to_models): - count_list = [] - for file in list(path_to_models.glob("*")): - try: - protein_id = str(file).split('-')[1] - count_list.append(protein_id) - except: - IndexError - count_dict = Counter(count_list) - count_dict = {';'.join(sorted(k for k in count_dict.keys() if count_dict[k] == v)): v for v in - set(count_dict.values())} - return count_dict \ No newline at end of file diff --git a/spaces/fcakyon/yolov8-segmentation/app.py b/spaces/fcakyon/yolov8-segmentation/app.py deleted file mode 100644 index 4868d290ea47ffe6eceb7bbdb23b8be2b94cc424..0000000000000000000000000000000000000000 --- a/spaces/fcakyon/yolov8-segmentation/app.py +++ /dev/null @@ -1,100 +0,0 @@ -import gradio as gr -import sahi -import torch -from ultralyticsplus import YOLO, render_model_output - -# Images -sahi.utils.file.download_from_url( - "https://raw.githubusercontent.com/kadirnar/dethub/main/data/images/highway.jpg", - "highway.jpg", -) -sahi.utils.file.download_from_url( - "https://raw.githubusercontent.com/obss/sahi/main/tests/data/small-vehicles1.jpeg", - "small-vehicles1.jpeg", -) -sahi.utils.file.download_from_url( - "https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg", - "zidane.jpg", -) - - -model_names = [ - "yolov8n-seg.pt", - "yolov8s-seg.pt", - "yolov8m-seg.pt", - "yolov8l-seg.pt", - "yolov8x-seg.pt", -] - -current_model_name = "yolov8m-seg.pt" -model = YOLO(current_model_name) - - -def yolov8_inference( - image: gr.inputs.Image = None, - model_name: gr.inputs.Dropdown = None, - image_size: gr.inputs.Slider = 640, - conf_threshold: gr.inputs.Slider = 0.25, - iou_threshold: gr.inputs.Slider = 0.45, -): - """ - YOLOv8 inference function - Args: - image: Input image - model_name: Name of the model - image_size: Image size - conf_threshold: Confidence threshold - iou_threshold: IOU threshold - Returns: - Rendered image - """ - global model - global current_model_name - if model_name != current_model_name: - model = YOLO(model_name) - current_model_name = model_name - model.overrides["conf"] = conf_threshold - model.overrides["iou"] = iou_threshold - results = model.predict(image, imgsz=image_size, return_outputs=True) - renders = [] - for image_results in model.predict(image, imgsz=image_size, return_outputs=True): - render = render_model_output( - model=model, image=image, model_output=image_results - ) - renders.append(render) - - return renders[0] - - -inputs = [ - gr.Image(type="filepath", label="Input Image"), - gr.Dropdown( - model_names, - value=current_model_name, - label="Model type", - ), - gr.Slider(minimum=320, maximum=1280, value=640, step=32, label="Image Size"), - gr.Slider( - minimum=0.0, maximum=1.0, value=0.25, step=0.05, label="Confidence Threshold" - ), - gr.Slider(minimum=0.0, maximum=1.0, value=0.45, step=0.05, label="IOU Threshold"), -] - -outputs = gr.Image(type="filepath", label="Output Image") -title = "Ultralytics YOLOv8 Segmentation Demo" - -examples = [ - ["zidane.jpg", "yolov8m-seg.pt", 640, 0.6, 0.45], - ["highway.jpg", "yolov8m-seg.pt", 640, 0.25, 0.45], - ["small-vehicles1.jpeg", "yolov8m-seg.pt", 640, 0.25, 0.45], -] -demo_app = gr.Interface( - fn=yolov8_inference, - inputs=inputs, - outputs=outputs, - title=title, - examples=examples, - cache_examples=True, - theme="default", -) -demo_app.launch(debug=True, enable_queue=True) diff --git a/spaces/fclong/summary/fengshen/data/bert_dataloader/preprocessing.py b/spaces/fclong/summary/fengshen/data/bert_dataloader/preprocessing.py deleted file mode 100644 index c40e39a8122a5cc4ebd57b558f451c371f6066a3..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/data/bert_dataloader/preprocessing.py +++ /dev/null @@ -1,110 +0,0 @@ -import re -import json -import multiprocessing -from tqdm import tqdm -from pathlib import Path -from itertools import chain - -_SPLIT_DATA_PATH = '/data1/datas/wudao_180g' - - -def cut_sent(path): - """ - 中文分句,默认?、。、!、省略号分句,考虑双引号包裹的句子 - 采用分割替换的方式 - """ - path = Path(path) - # print(path) - save_path = str(Path('/data1/datas/wudao_180g_split', path.name)) - print('处理文件:', save_path) - with open(save_path, 'wt', encoding='utf-8') as w: - with open(path, 'rt', encoding='utf-8') as f: - for para in tqdm(f): - para = json.loads(para) - para_ = para['text'] + ' ' - # print('sentence piece......') - # pep8中 正则不能些 \? 要写成\\? - para_ = re.sub('([?。!\\?\\!…]+)([^”’]|[”’])', - r'\1#####\2', para_) - para_ = re.sub('([\\.]{3,})([^”’])', r'\1#####\2', para_) - - # 匹配 \1: 句子结束符紧挨’” \2: 非句子结束符号,被引号包裹的句子 - para_ = re.sub( - '([。!?\\?\\!…][”’])([^,。!?\\?\\!]|\\s)', r'\1#####\2', para_) - para_ = re.sub( - '([\\.]{3,}[”’])([^,。!?\\?\\!]|\\s)', r'\1#####\2', para_) - para_ = re.sub( - '([#]{5})([”’])([^,。!?\\?\\!])', r'\2#####\3', para_) - para_ = para_.strip() - # 一个512里面多个样本 - line_ = '' - for line in para_.split('#####'): - line = line.strip() - if len(line_) < 512 and len(line) > 0: - line_ += line - else: - w.writelines(json.dumps( - {'text': line_}, ensure_ascii=False)+'\n') - line_ = line - w.writelines(json.dumps( - {'text': line_}, ensure_ascii=False)+'\n') - - -def chain_iter(*filenames): - """ - 将多个文件读成一个迭代器 - """ - reader = [open(file, 'r') for file in filenames] - return chain(*reader) - - -class Config(object): - - def __init__(self, data_path=_SPLIT_DATA_PATH, num_worker=16, split_numb=600000, cut_sentence=True, output_file=None) -> None: - self.data_path = Path(data_path) - self.num_worker = num_worker - self.split_numb = split_numb - self.cut_sentence = cut_sentence - - -def processing1(): - args = Config() - p_ = [str(i) for i in args.data_path.glob('*')] - fin = chain_iter(*p_) - pool = multiprocessing.Pool(args.num_worker) - docs = pool.imap(cut_sent, fin, chunksize=args.num_worker) - - if not Path(args.data_path.parent, args.data_path.name+'_split').exists(): - Path(args.data_path.parent, args.data_path.name+'_split').mkdir() - writer = open(str(Path(args.data_path.parent, args.data_path.name + - '_split', 'sentence_level.json')), 'wt', encoding='utf-8') - for doc in tqdm(docs): - for sentence in doc: - writer.writelines(json.dumps( - {"text": sentence}, ensure_ascii=False)+'\n') - pool.close() - pool.join() - writer.close() - - -if __name__ == '__main__': - from time import process_time, perf_counter - from random import shuffle - st = process_time() - args = Config(num_worker=16) - - if not Path(args.data_path.parent, args.data_path.name+'_split').exists(): - Path(args.data_path.parent, args.data_path.name + - '_split').mkdir(parents=True) - - p_ = [str(i) for i in args.data_path.glob('*')] - # 简单shuffle - shuffle(p_) - - pool = multiprocessing.Pool(args.num_worker) - for item in p_: - pool.apply_async(func=cut_sent, args=(item,)) - pool.close() - pool.join() - cost_time = process_time() - st - print('DONE!! cost time : %.5f' % cost_time) diff --git a/spaces/fclong/summary/fengshen/data/universal_datamodule/__init__.py b/spaces/fclong/summary/fengshen/data/universal_datamodule/__init__.py deleted file mode 100644 index 68169d26a8424ae877b5c7efc2b7be2e761cd3cb..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/data/universal_datamodule/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .universal_datamodule import UniversalDataModule -from .universal_sampler import PretrainingSampler, PretrainingRandomSampler - -__all__ = ['UniversalDataModule', 'PretrainingSampler', 'PretrainingRandomSampler'] diff --git a/spaces/fclong/summary/fengshen/examples/clue1.1/predict2submit/iflytek_submit.py b/spaces/fclong/summary/fengshen/examples/clue1.1/predict2submit/iflytek_submit.py deleted file mode 100644 index d0c9c8220b01bd1bc5068bb5101be4871d238924..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/examples/clue1.1/predict2submit/iflytek_submit.py +++ /dev/null @@ -1,160 +0,0 @@ -import json -from tqdm import tqdm -import argparse - - -def save_data(data,file_path): - with open(file_path, 'w', encoding='utf8') as f: - for line in data: - json_data=json.dumps(line,ensure_ascii=False) - f.write(json_data+'\n') - - -label2id={"打车": "0", "地图导航": "1", "免费WIFI": "2", "租车": "3", "同城服务": "4", "快递物流": "5", "婚庆": "6", "家政": "7", "公共交通": "8", "政务": "9", "社区服务": "10", "薅羊毛": "11", "魔幻": "12", "仙侠": "13", "卡牌": "14", "飞行空战": "15", "射击游戏": "16", "休闲益智": "17", "动作类": "18", "体育竞技": "19", "棋牌中心": "20", "经营养成": "21", "策略": "22", "MOBA": "23", "辅助工具": "24", "约会社交": "25", "即时通讯": "26", "工作社交": "27", "论坛圈子": "28", "婚恋社交": "29", "情侣社交": "30", "社交工具": "31", "生活社交": "32", "微博博客": "33", "新闻": "34", "漫画": "35", "小说": "36", "技术": "37", "教辅": "38", "问答交流": "39", "搞笑": "40", "杂志": "41", "百科": "42", "影视娱乐": "43", "求职": "44", "兼职": "45", "视频": "46", "短视频": "47", "音乐": "48", "直播": "49", "电台": "50", "K歌": "51", "成人": "52", "中小学": "53", "职考": "54", "公务员": "55", "英语": "56", "视频教育": "57", "高等教育": "58", "成人教育": "59", "艺术": "60", "语言(非英语)": "61", "旅游资讯": "62", "综合预定": "63", "民航": "64", "铁路": "65", "酒店": "66", "行程管理": "67", "民宿短租": "68", "出国": "69", "工具": "70", "亲子儿童": "71", "母婴": "72", "驾校": "73", "违章": "74", "汽车咨询": "75", "汽车交易": "76", "日常养车": "77", "行车辅助": "78", "租房": "79", "买房": "80", "装修家居": "81", "电子产品": "82", "问诊挂号": "83", "养生保健": "84", "医疗服务": "85", "减肥瘦身": "86", "美妆美业": "87", "菜谱": "88", "餐饮店": "89", "体育咨讯": "90", "运动健身": "91", "支付": "92", "保险": "93", "股票": "94", "借贷": "95", "理财": "96", "彩票": "97", "记账": "98", "银行": "99", "美颜": "100", "影像剪辑": "101", "摄影修图": "102", "相机": "103", "绘画": "104", "二手": "105", "电商": "106", "团购": "107", "外卖": "108", "电影票务": "109", "社区超市": "110", "购物咨询": "111", "笔记": "112", "办公": "113", "日程管理": "114", "女性": "115", "经营": "116", "收款": "117", "其他": "118"} - -label2desc={ - '银行': '银行', - '社区服务': '社区', - '电商': '电商', - '支付': '支付', - '经营养成': '养成', - '卡牌': '卡牌', - '借贷': '借贷', - '驾校': '驾校', - '理财': '理财', - '职考': '职考', - '新闻': '新闻', - '旅游资讯': '旅游', - '公共交通': '交通', - '魔幻': '魔幻', - '医疗服务': '医疗', - '影像剪辑': '影像', - '动作类': '动作', - '工具': '工具', - '体育竞技': '体育', - '小说': '小说', - '运动健身': '运动', - '相机': '相机', - '辅助工具': '辅助', - '快递物流': '快递', - '高等教育': '教育', - '股票': '股票', - '菜谱': '菜谱', - '行车辅助': '行车', - '仙侠': '仙侠', - '亲子儿童': '亲子', - '购物咨询': '购物', - '射击游戏': '射击', - '漫画': '漫画', - '中小学': '小学', - '同城服务': '同城', - '成人教育': '成人', - '求职': '求职', - '电子产品': '电子', - '艺术': '艺术', - '薅羊毛': '赚钱', - '约会社交': '约会', - '经营': '经营', - '兼职': '兼职', - '短视频': '短视', - '音乐': '音乐', - '英语': '英语', - '棋牌中心': '棋牌', - '摄影修图': '摄影', - '养生保健': '养生', - '办公': '办公', - '政务': '政务', - '视频': '视频', - '论坛圈子': '论坛', - '彩票': '彩票', - '直播': '直播', - '其他': '其他', - '休闲益智': '休闲', - '策略': '策略', - '即时通讯': '通讯', - '汽车交易': '买车', - '违章': '违章', - '地图导航': '地图', - '民航': '民航', - '电台': '电台', - '语言(非英语)': '语言', - '搞笑': '搞笑', - '婚恋社交': '婚恋', - '社区超市': '超市', - '日常养车': '养车', - '杂志': '杂志', - '视频教育': '在线', - '家政': '家政', - '影视娱乐': '影视', - '装修家居': '装修', - '体育咨讯': '资讯', - '社交工具': '社交', - '餐饮店': '餐饮', - '美颜': '美颜', - '问诊挂号': '挂号', - '飞行空战': '飞行', - '综合预定': '预定', - '电影票务': '票务', - '笔记': '笔记', - '买房': '买房', - '外卖': '外卖', - '母婴': '母婴', - '打车': '打车', - '情侣社交': '情侣', - '日程管理': '日程', - '租车': '租车', - '微博博客': '博客', - '百科': '百科', - '绘画': '绘画', - '铁路': '铁路', - '生活社交': '生活', - '租房': '租房', - '酒店': '酒店', - '保险': '保险', - '问答交流': '问答', - '收款': '收款', - 'MOBA': '竞技', - 'K歌': '唱歌', - '技术': '技术', - '减肥瘦身': '减肥', - '工作社交': '工作', - '团购': '团购', - '记账': '记账', - '女性': '女性', - '公务员': '公务', - '二手': '二手', - '美妆美业': '美妆', - '汽车咨询': '汽车', - '行程管理': '行程', - '免费WIFI': '免费', - '教辅': '教辅', - '成人': '两性', - '出国': '出国', - '婚庆': '婚庆', - '民宿短租': '民宿'} - -desc2label={v:k for k,v in label2desc.items()} - - - -def submit(file_path): - with open(file_path, 'r', encoding='utf8') as f: - lines = f.readlines() - result=[] - for line in tqdm(lines): - data = json.loads(line) - result.append({'id':data['id'],'label':label2id[desc2label[data['choice'][data['label']]]]}) - return result - - - - -if __name__=="__main__": - parser = argparse.ArgumentParser(description="train") - parser.add_argument("--data_path", type=str,default="") - parser.add_argument("--save_path", type=str,default="") - - args = parser.parse_args() - save_data(submit(args.data_path), args.save_path) - - \ No newline at end of file diff --git a/spaces/fuxin123zz/ChuanhuChatGPT/run_macOS.command b/spaces/fuxin123zz/ChuanhuChatGPT/run_macOS.command deleted file mode 100644 index 62af07283093d8e580763d7acfe493c3d88e7b08..0000000000000000000000000000000000000000 --- a/spaces/fuxin123zz/ChuanhuChatGPT/run_macOS.command +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# 获取脚本所在目录 -script_dir=$(dirname "$0") - -# 将工作目录更改为脚本所在目录 -cd "$script_dir" - -# 检查Git仓库是否有更新 -git remote update -pwd - -if ! git status -uno | grep 'up to date' > /dev/null; then - # 如果有更新,关闭当前运行的服务器 - pkill -f ChuanhuChatbot.py - - # 拉取最新更改 - git pull - - # 安装依赖 - pip3 install -r requirements.txt - - # 重新启动服务器 - nohup python3 ChuanhuChatbot.py & -fi diff --git a/spaces/g4f/freegpt-webui/g4f/Provider/Providers/Vercel.py b/spaces/g4f/freegpt-webui/g4f/Provider/Providers/Vercel.py deleted file mode 100644 index e5df9cf017e4c1a265f5c9d5e48eb5c10a56e60a..0000000000000000000000000000000000000000 --- a/spaces/g4f/freegpt-webui/g4f/Provider/Providers/Vercel.py +++ /dev/null @@ -1,162 +0,0 @@ -import os -import json -import base64 -import execjs -import queue -import threading - -from curl_cffi import requests -from ...typing import sha256, Dict, get_type_hints - -url = 'https://play.vercel.ai' -supports_stream = True -needs_auth = False - -models = { - 'claude-instant-v1': 'anthropic:claude-instant-v1', - 'claude-v1': 'anthropic:claude-v1', - 'alpaca-7b': 'replicate:replicate/alpaca-7b', - 'stablelm-tuned-alpha-7b': 'replicate:stability-ai/stablelm-tuned-alpha-7b', - 'bloom': 'huggingface:bigscience/bloom', - 'bloomz': 'huggingface:bigscience/bloomz', - 'flan-t5-xxl': 'huggingface:google/flan-t5-xxl', - 'flan-ul2': 'huggingface:google/flan-ul2', - 'gpt-neox-20b': 'huggingface:EleutherAI/gpt-neox-20b', - 'oasst-sft-4-pythia-12b-epoch-3.5': 'huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5', - 'santacoder': 'huggingface:bigcode/santacoder', - 'command-medium-nightly': 'cohere:command-medium-nightly', - 'command-xlarge-nightly': 'cohere:command-xlarge-nightly', - 'code-cushman-001': 'openai:code-cushman-001', - 'code-davinci-002': 'openai:code-davinci-002', - 'gpt-3.5-turbo': 'openai:gpt-3.5-turbo', - 'text-ada-001': 'openai:text-ada-001', - 'text-babbage-001': 'openai:text-babbage-001', - 'text-curie-001': 'openai:text-curie-001', - 'text-davinci-002': 'openai:text-davinci-002', - 'text-davinci-003': 'openai:text-davinci-003' -} -model = models.keys() - -vercel_models = {'anthropic:claude-instant-v1': {'id': 'anthropic:claude-instant-v1', 'provider': 'anthropic', 'providerHumanName': 'Anthropic', 'makerHumanName': 'Anthropic', 'minBillingTier': 'hobby', 'parameters': {'temperature': {'value': 1, 'range': [0, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'topK': {'value': 1, 'range': [1, 500]}, 'presencePenalty': {'value': 1, 'range': [0, 1]}, 'frequencyPenalty': {'value': 1, 'range': [0, 1]}, 'stopSequences': {'value': ['\n\nHuman:'], 'range': []}}, 'name': 'claude-instant-v1'}, 'anthropic:claude-v1': {'id': 'anthropic:claude-v1', 'provider': 'anthropic', 'providerHumanName': 'Anthropic', 'makerHumanName': 'Anthropic', 'minBillingTier': 'hobby', 'parameters': {'temperature': {'value': 1, 'range': [0, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'topK': {'value': 1, 'range': [1, 500]}, 'presencePenalty': {'value': 1, 'range': [0, 1]}, 'frequencyPenalty': {'value': 1, 'range': [0, 1]}, 'stopSequences': {'value': ['\n\nHuman:'], 'range': []}}, 'name': 'claude-v1'}, 'replicate:replicate/alpaca-7b': {'id': 'replicate:replicate/alpaca-7b', 'provider': 'replicate', 'providerHumanName': 'Replicate', 'makerHumanName': 'Stanford', 'parameters': {'temperature': {'value': 0.75, 'range': [0.01, 5]}, 'maximumLength': {'value': 200, 'range': [50, 512]}, 'topP': {'value': 0.95, 'range': [0.01, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'repetitionPenalty': {'value': 1.1765, 'range': [0.01, 5]}, 'stopSequences': {'value': [], 'range': []}}, 'version': '2014ee1247354f2e81c0b3650d71ca715bc1e610189855f134c30ecb841fae21', 'name': 'alpaca-7b'}, 'replicate:stability-ai/stablelm-tuned-alpha-7b': {'id': 'replicate:stability-ai/stablelm-tuned-alpha-7b', 'provider': 'replicate', 'makerHumanName': 'StabilityAI', 'providerHumanName': 'Replicate', 'parameters': {'temperature': {'value': 0.75, 'range': [0.01, 5]}, 'maximumLength': {'value': 200, 'range': [50, 512]}, 'topP': {'value': 0.95, 'range': [0.01, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'repetitionPenalty': {'value': 1.1765, 'range': [0.01, 5]}, 'stopSequences': {'value': [], 'range': []}}, 'version': '4a9a32b4fd86c2d047f1d271fa93972683ec6ef1cf82f402bd021f267330b50b', 'name': 'stablelm-tuned-alpha-7b'}, 'huggingface:bigscience/bloom': {'id': 'huggingface:bigscience/bloom', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'BigScience', 'instructions': "Do NOT talk to Bloom as an entity, it's not a chatbot but a webpage/blog/article completion model. For the best results: mimic a few words of a webpage similar to the content you want to generate. Start a sentence as if YOU were writing a blog, webpage, math post, coding article and Bloom will generate a coherent follow-up.", 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'bloom'}, 'huggingface:bigscience/bloomz': {'id': 'huggingface:bigscience/bloomz', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'BigScience', 'instructions': 'We recommend using the model to perform tasks expressed in natural language. For example, given the prompt "Translate to English: Je t\'aime.", the model will most likely answer "I love you.".', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'bloomz'}, 'huggingface:google/flan-t5-xxl': {'id': 'huggingface:google/flan-t5-xxl', 'provider': 'huggingface', 'makerHumanName': 'Google', 'providerHumanName': 'HuggingFace', 'name': 'flan-t5-xxl', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}}, 'huggingface:google/flan-ul2': {'id': 'huggingface:google/flan-ul2', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'Google', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'flan-ul2'}, 'huggingface:EleutherAI/gpt-neox-20b': {'id': 'huggingface:EleutherAI/gpt-neox-20b', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'EleutherAI', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'gpt-neox-20b'}, 'huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5': {'id': 'huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'OpenAssistant', 'parameters': {'maximumLength': {'value': 200, 'range': [50, 1024]}, 'typicalP': {'value': 0.2, 'range': [0.1, 0.99]}, 'repetitionPenalty': {'value': 1, 'range': [0.1, 2]}}, 'name': 'oasst-sft-4-pythia-12b-epoch-3.5'}, 'huggingface:bigcode/santacoder': { - 'id': 'huggingface:bigcode/santacoder', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'BigCode', 'instructions': 'The model was trained on GitHub code. As such it is not an instruction model and commands like "Write a function that computes the square root." do not work well. You should phrase commands like they occur in source code such as comments (e.g. # the following function computes the sqrt) or write a function signature and docstring and let the model complete the function body.', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'santacoder'}, 'cohere:command-medium-nightly': {'id': 'cohere:command-medium-nightly', 'provider': 'cohere', 'providerHumanName': 'Cohere', 'makerHumanName': 'Cohere', 'name': 'command-medium-nightly', 'parameters': {'temperature': {'value': 0.9, 'range': [0, 2]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0, 1]}, 'topK': {'value': 0, 'range': [0, 500]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'cohere:command-xlarge-nightly': {'id': 'cohere:command-xlarge-nightly', 'provider': 'cohere', 'providerHumanName': 'Cohere', 'makerHumanName': 'Cohere', 'name': 'command-xlarge-nightly', 'parameters': {'temperature': {'value': 0.9, 'range': [0, 2]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0, 1]}, 'topK': {'value': 0, 'range': [0, 500]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:gpt-4': {'id': 'openai:gpt-4', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'gpt-4', 'minBillingTier': 'pro', 'parameters': {'temperature': {'value': 0.7, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:code-cushman-001': {'id': 'openai:code-cushman-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'code-cushman-001'}, 'openai:code-davinci-002': {'id': 'openai:code-davinci-002', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'code-davinci-002'}, 'openai:gpt-3.5-turbo': {'id': 'openai:gpt-3.5-turbo', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'parameters': {'temperature': {'value': 0.7, 'range': [0, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'topK': {'value': 1, 'range': [1, 500]}, 'presencePenalty': {'value': 1, 'range': [0, 1]}, 'frequencyPenalty': {'value': 1, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'gpt-3.5-turbo'}, 'openai:text-ada-001': {'id': 'openai:text-ada-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-ada-001', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-babbage-001': {'id': 'openai:text-babbage-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-babbage-001', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-curie-001': {'id': 'openai:text-curie-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-curie-001', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-davinci-002': {'id': 'openai:text-davinci-002', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-davinci-002', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-davinci-003': {'id': 'openai:text-davinci-003', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-davinci-003', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}} - - -# based on https://github.com/ading2210/vercel-llm-api // modified -class Client: - def __init__(self): - self.session = requests.Session() - self.headers = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110 Safari/537.36', - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', - 'Accept-Encoding': 'gzip, deflate, br', - 'Accept-Language': 'en-US,en;q=0.5', - 'Te': 'trailers', - 'Upgrade-Insecure-Requests': '1' - } - self.session.headers.update(self.headers) - - def get_token(self): - b64 = self.session.get('https://sdk.vercel.ai/openai.jpeg').text - data = json.loads(base64.b64decode(b64)) - - code = 'const globalThis = {data: `sentinel`}; function token() {return (%s)(%s)}' % ( - data['c'], data['a']) - - token_string = json.dumps(separators=(',', ':'), - obj={'r': execjs.compile(code).call('token'), 't': data['t']}) - - return base64.b64encode(token_string.encode()).decode() - - def get_default_params(self, model_id): - return {key: param['value'] for key, param in vercel_models[model_id]['parameters'].items()} - - def generate(self, model_id: str, prompt: str, params: dict = {}): - if not ':' in model_id: - model_id = models[model_id] - - defaults = self.get_default_params(model_id) - - payload = defaults | params | { - 'prompt': prompt, - 'model': model_id, - } - - headers = self.headers | { - 'Accept-Encoding': 'gzip, deflate, br', - 'Custom-Encoding': self.get_token(), - 'Host': 'sdk.vercel.ai', - 'Origin': 'https://sdk.vercel.ai', - 'Referrer': 'https://sdk.vercel.ai', - 'Sec-Fetch-Dest': 'empty', - 'Sec-Fetch-Mode': 'cors', - 'Sec-Fetch-Site': 'same-origin', - } - - chunks_queue = queue.Queue() - error = None - response = None - - def callback(data): - chunks_queue.put(data.decode()) - - def request_thread(): - nonlocal response, error - for _ in range(3): - try: - response = self.session.post('https://sdk.vercel.ai/api/generate', - json=payload, headers=headers, content_callback=callback) - response.raise_for_status() - - except Exception as e: - if _ == 2: - error = e - - else: - continue - - thread = threading.Thread(target=request_thread, daemon=True) - thread.start() - - text = '' - index = 0 - while True: - try: - chunk = chunks_queue.get(block=True, timeout=0.1) - - except queue.Empty: - if error: - raise error - - elif response: - break - - else: - continue - - text += chunk - lines = text.split('\n') - - if len(lines) - 1 > index: - new = lines[index:-1] - for word in new: - yield json.loads(word) - index = len(lines) - 1 - -def _create_completion(model: str, messages: list, stream: bool, **kwargs): - yield 'Vercel is currently not working.' - return - - conversation = 'This is a conversation between a human and a language model, respond to the last message accordingly, referring to the past history of messages if needed.\n' - - for message in messages: - conversation += '%s: %s\n' % (message['role'], message['content']) - - conversation += 'assistant: ' - - completion = Client().generate(model, conversation) - - for token in completion: - yield token - -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/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmcv/runner/optimizer/__init__.py b/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmcv/runner/optimizer/__init__.py deleted file mode 100644 index 53c34d0470992cbc374f29681fdd00dc0e57968d..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmcv/runner/optimizer/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .builder import (OPTIMIZER_BUILDERS, OPTIMIZERS, build_optimizer, - build_optimizer_constructor) -from .default_constructor import DefaultOptimizerConstructor - -__all__ = [ - 'OPTIMIZER_BUILDERS', 'OPTIMIZERS', 'DefaultOptimizerConstructor', - 'build_optimizer', 'build_optimizer_constructor' -] diff --git a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmcv/runner/optimizer/default_constructor.py b/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmcv/runner/optimizer/default_constructor.py deleted file mode 100644 index 2c0da3503b75441738efe38d70352b55a210a34a..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmcv/runner/optimizer/default_constructor.py +++ /dev/null @@ -1,249 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import warnings - -import torch -from torch.nn import GroupNorm, LayerNorm - -from annotator.uniformer.mmcv.utils import _BatchNorm, _InstanceNorm, build_from_cfg, is_list_of -from annotator.uniformer.mmcv.utils.ext_loader import check_ops_exist -from .builder import OPTIMIZER_BUILDERS, OPTIMIZERS - - -@OPTIMIZER_BUILDERS.register_module() -class DefaultOptimizerConstructor: - """Default constructor for optimizers. - - By default each parameter share the same optimizer settings, and we - provide an argument ``paramwise_cfg`` to specify parameter-wise settings. - It is a dict and may contain the following fields: - - - ``custom_keys`` (dict): Specified parameters-wise settings by keys. If - one of the keys in ``custom_keys`` is a substring of the name of one - parameter, then the setting of the parameter will be specified by - ``custom_keys[key]`` and other setting like ``bias_lr_mult`` etc. will - be ignored. It should be noted that the aforementioned ``key`` is the - longest key that is a substring of the name of the parameter. If there - are multiple matched keys with the same length, then the key with lower - alphabet order will be chosen. - ``custom_keys[key]`` should be a dict and may contain fields ``lr_mult`` - and ``decay_mult``. See Example 2 below. - - ``bias_lr_mult`` (float): It will be multiplied to the learning - rate for all bias parameters (except for those in normalization - layers and offset layers of DCN). - - ``bias_decay_mult`` (float): It will be multiplied to the weight - decay for all bias parameters (except for those in - normalization layers, depthwise conv layers, offset layers of DCN). - - ``norm_decay_mult`` (float): It will be multiplied to the weight - decay for all weight and bias parameters of normalization - layers. - - ``dwconv_decay_mult`` (float): It will be multiplied to the weight - decay for all weight and bias parameters of depthwise conv - layers. - - ``dcn_offset_lr_mult`` (float): It will be multiplied to the learning - rate for parameters of offset layer in the deformable convs - of a model. - - ``bypass_duplicate`` (bool): If true, the duplicate parameters - would not be added into optimizer. Default: False. - - Note: - 1. If the option ``dcn_offset_lr_mult`` is used, the constructor will - override the effect of ``bias_lr_mult`` in the bias of offset - layer. So be careful when using both ``bias_lr_mult`` and - ``dcn_offset_lr_mult``. If you wish to apply both of them to the - offset layer in deformable convs, set ``dcn_offset_lr_mult`` - to the original ``dcn_offset_lr_mult`` * ``bias_lr_mult``. - 2. If the option ``dcn_offset_lr_mult`` is used, the constructor will - apply it to all the DCN layers in the model. So be careful when - the model contains multiple DCN layers in places other than - backbone. - - Args: - model (:obj:`nn.Module`): The model with parameters to be optimized. - optimizer_cfg (dict): The config dict of the optimizer. - Positional fields are - - - `type`: class name of the optimizer. - - Optional fields are - - - any arguments of the corresponding optimizer type, e.g., - lr, weight_decay, momentum, etc. - paramwise_cfg (dict, optional): Parameter-wise options. - - Example 1: - >>> model = torch.nn.modules.Conv1d(1, 1, 1) - >>> optimizer_cfg = dict(type='SGD', lr=0.01, momentum=0.9, - >>> weight_decay=0.0001) - >>> paramwise_cfg = dict(norm_decay_mult=0.) - >>> optim_builder = DefaultOptimizerConstructor( - >>> optimizer_cfg, paramwise_cfg) - >>> optimizer = optim_builder(model) - - Example 2: - >>> # assume model have attribute model.backbone and model.cls_head - >>> optimizer_cfg = dict(type='SGD', lr=0.01, weight_decay=0.95) - >>> paramwise_cfg = dict(custom_keys={ - '.backbone': dict(lr_mult=0.1, decay_mult=0.9)}) - >>> optim_builder = DefaultOptimizerConstructor( - >>> optimizer_cfg, paramwise_cfg) - >>> optimizer = optim_builder(model) - >>> # Then the `lr` and `weight_decay` for model.backbone is - >>> # (0.01 * 0.1, 0.95 * 0.9). `lr` and `weight_decay` for - >>> # model.cls_head is (0.01, 0.95). - """ - - def __init__(self, optimizer_cfg, paramwise_cfg=None): - if not isinstance(optimizer_cfg, dict): - raise TypeError('optimizer_cfg should be a dict', - f'but got {type(optimizer_cfg)}') - self.optimizer_cfg = optimizer_cfg - self.paramwise_cfg = {} if paramwise_cfg is None else paramwise_cfg - self.base_lr = optimizer_cfg.get('lr', None) - self.base_wd = optimizer_cfg.get('weight_decay', None) - self._validate_cfg() - - def _validate_cfg(self): - if not isinstance(self.paramwise_cfg, dict): - raise TypeError('paramwise_cfg should be None or a dict, ' - f'but got {type(self.paramwise_cfg)}') - - if 'custom_keys' in self.paramwise_cfg: - if not isinstance(self.paramwise_cfg['custom_keys'], dict): - raise TypeError( - 'If specified, custom_keys must be a dict, ' - f'but got {type(self.paramwise_cfg["custom_keys"])}') - if self.base_wd is None: - for key in self.paramwise_cfg['custom_keys']: - if 'decay_mult' in self.paramwise_cfg['custom_keys'][key]: - raise ValueError('base_wd should not be None') - - # get base lr and weight decay - # weight_decay must be explicitly specified if mult is specified - if ('bias_decay_mult' in self.paramwise_cfg - or 'norm_decay_mult' in self.paramwise_cfg - or 'dwconv_decay_mult' in self.paramwise_cfg): - if self.base_wd is None: - raise ValueError('base_wd should not be None') - - def _is_in(self, param_group, param_group_list): - assert is_list_of(param_group_list, dict) - param = set(param_group['params']) - param_set = set() - for group in param_group_list: - param_set.update(set(group['params'])) - - return not param.isdisjoint(param_set) - - def add_params(self, params, module, prefix='', is_dcn_module=None): - """Add all parameters of module to the params list. - - The parameters of the given module will be added to the list of param - groups, with specific rules defined by paramwise_cfg. - - Args: - params (list[dict]): A list of param groups, it will be modified - in place. - module (nn.Module): The module to be added. - prefix (str): The prefix of the module - is_dcn_module (int|float|None): If the current module is a - submodule of DCN, `is_dcn_module` will be passed to - control conv_offset layer's learning rate. Defaults to None. - """ - # get param-wise options - custom_keys = self.paramwise_cfg.get('custom_keys', {}) - # first sort with alphabet order and then sort with reversed len of str - sorted_keys = sorted(sorted(custom_keys.keys()), key=len, reverse=True) - - bias_lr_mult = self.paramwise_cfg.get('bias_lr_mult', 1.) - bias_decay_mult = self.paramwise_cfg.get('bias_decay_mult', 1.) - norm_decay_mult = self.paramwise_cfg.get('norm_decay_mult', 1.) - dwconv_decay_mult = self.paramwise_cfg.get('dwconv_decay_mult', 1.) - bypass_duplicate = self.paramwise_cfg.get('bypass_duplicate', False) - dcn_offset_lr_mult = self.paramwise_cfg.get('dcn_offset_lr_mult', 1.) - - # special rules for norm layers and depth-wise conv layers - is_norm = isinstance(module, - (_BatchNorm, _InstanceNorm, GroupNorm, LayerNorm)) - is_dwconv = ( - isinstance(module, torch.nn.Conv2d) - and module.in_channels == module.groups) - - for name, param in module.named_parameters(recurse=False): - param_group = {'params': [param]} - if not param.requires_grad: - params.append(param_group) - continue - if bypass_duplicate and self._is_in(param_group, params): - warnings.warn(f'{prefix} is duplicate. It is skipped since ' - f'bypass_duplicate={bypass_duplicate}') - continue - # if the parameter match one of the custom keys, ignore other rules - is_custom = False - for key in sorted_keys: - if key in f'{prefix}.{name}': - is_custom = True - lr_mult = custom_keys[key].get('lr_mult', 1.) - param_group['lr'] = self.base_lr * lr_mult - if self.base_wd is not None: - decay_mult = custom_keys[key].get('decay_mult', 1.) - param_group['weight_decay'] = self.base_wd * decay_mult - break - - if not is_custom: - # bias_lr_mult affects all bias parameters - # except for norm.bias dcn.conv_offset.bias - if name == 'bias' and not (is_norm or is_dcn_module): - param_group['lr'] = self.base_lr * bias_lr_mult - - if (prefix.find('conv_offset') != -1 and is_dcn_module - and isinstance(module, torch.nn.Conv2d)): - # deal with both dcn_offset's bias & weight - param_group['lr'] = self.base_lr * dcn_offset_lr_mult - - # apply weight decay policies - if self.base_wd is not None: - # norm decay - if is_norm: - param_group[ - 'weight_decay'] = self.base_wd * norm_decay_mult - # depth-wise conv - elif is_dwconv: - param_group[ - 'weight_decay'] = self.base_wd * dwconv_decay_mult - # bias lr and decay - elif name == 'bias' and not is_dcn_module: - # TODO: current bias_decay_mult will have affect on DCN - param_group[ - 'weight_decay'] = self.base_wd * bias_decay_mult - params.append(param_group) - - if check_ops_exist(): - from annotator.uniformer.mmcv.ops import DeformConv2d, ModulatedDeformConv2d - is_dcn_module = isinstance(module, - (DeformConv2d, ModulatedDeformConv2d)) - else: - is_dcn_module = False - for child_name, child_mod in module.named_children(): - child_prefix = f'{prefix}.{child_name}' if prefix else child_name - self.add_params( - params, - child_mod, - prefix=child_prefix, - is_dcn_module=is_dcn_module) - - def __call__(self, model): - if hasattr(model, 'module'): - model = model.module - - optimizer_cfg = self.optimizer_cfg.copy() - # if no paramwise option is specified, just use the global setting - if not self.paramwise_cfg: - optimizer_cfg['params'] = model.parameters() - return build_from_cfg(optimizer_cfg, OPTIMIZERS) - - # set param-wise lr and weight decay recursively - params = [] - self.add_params(params, model) - optimizer_cfg['params'] = params - - return build_from_cfg(optimizer_cfg, OPTIMIZERS) diff --git a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmseg/datasets/pascal_context.py b/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmseg/datasets/pascal_context.py deleted file mode 100644 index 541a63c66a13fb16fd52921e755715ad8d078fdd..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmseg/datasets/pascal_context.py +++ /dev/null @@ -1,103 +0,0 @@ -import os.path as osp - -from .builder import DATASETS -from .custom import CustomDataset - - -@DATASETS.register_module() -class PascalContextDataset(CustomDataset): - """PascalContext dataset. - - In segmentation map annotation for PascalContext, 0 stands for background, - which is included in 60 categories. ``reduce_zero_label`` is fixed to - False. The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is - fixed to '.png'. - - Args: - split (str): Split txt file for PascalContext. - """ - - CLASSES = ('background', 'aeroplane', 'bag', 'bed', 'bedclothes', 'bench', - 'bicycle', 'bird', 'boat', 'book', 'bottle', 'building', 'bus', - 'cabinet', 'car', 'cat', 'ceiling', 'chair', 'cloth', - 'computer', 'cow', 'cup', 'curtain', 'dog', 'door', 'fence', - 'floor', 'flower', 'food', 'grass', 'ground', 'horse', - 'keyboard', 'light', 'motorbike', 'mountain', 'mouse', 'person', - 'plate', 'platform', 'pottedplant', 'road', 'rock', 'sheep', - 'shelves', 'sidewalk', 'sign', 'sky', 'snow', 'sofa', 'table', - 'track', 'train', 'tree', 'truck', 'tvmonitor', 'wall', 'water', - 'window', 'wood') - - PALETTE = [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], - [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], - [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], - [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], - [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], - [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255], - [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220], - [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224], - [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], - [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7], - [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], - [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255], - [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0], - [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255], - [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255]] - - def __init__(self, split, **kwargs): - super(PascalContextDataset, self).__init__( - img_suffix='.jpg', - seg_map_suffix='.png', - split=split, - reduce_zero_label=False, - **kwargs) - assert osp.exists(self.img_dir) and self.split is not None - - -@DATASETS.register_module() -class PascalContextDataset59(CustomDataset): - """PascalContext dataset. - - In segmentation map annotation for PascalContext, 0 stands for background, - which is included in 60 categories. ``reduce_zero_label`` is fixed to - False. The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is - fixed to '.png'. - - Args: - split (str): Split txt file for PascalContext. - """ - - CLASSES = ('aeroplane', 'bag', 'bed', 'bedclothes', 'bench', 'bicycle', - 'bird', 'boat', 'book', 'bottle', 'building', 'bus', 'cabinet', - 'car', 'cat', 'ceiling', 'chair', 'cloth', 'computer', 'cow', - 'cup', 'curtain', 'dog', 'door', 'fence', 'floor', 'flower', - 'food', 'grass', 'ground', 'horse', 'keyboard', 'light', - 'motorbike', 'mountain', 'mouse', 'person', 'plate', 'platform', - 'pottedplant', 'road', 'rock', 'sheep', 'shelves', 'sidewalk', - 'sign', 'sky', 'snow', 'sofa', 'table', 'track', 'train', - 'tree', 'truck', 'tvmonitor', 'wall', 'water', 'window', 'wood') - - PALETTE = [[180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], - [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], - [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], - [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, 255, 140], - [204, 255, 4], [255, 51, 7], [204, 70, 3], [0, 102, 200], - [61, 230, 250], [255, 6, 51], [11, 102, 255], [255, 7, 71], - [255, 9, 224], [9, 7, 230], [220, 220, 220], [255, 9, 92], - [112, 9, 255], [8, 255, 214], [7, 255, 224], [255, 184, 6], - [10, 255, 71], [255, 41, 10], [7, 255, 255], [224, 255, 8], - [102, 8, 255], [255, 61, 6], [255, 194, 7], [255, 122, 8], - [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], - [235, 12, 255], [160, 150, 20], [0, 163, 255], [140, 140, 140], - [250, 10, 15], [20, 255, 0], [31, 255, 0], [255, 31, 0], - [255, 224, 0], [153, 255, 0], [0, 0, 255], [255, 71, 0], - [0, 235, 255], [0, 173, 255], [31, 0, 255]] - - def __init__(self, split, **kwargs): - super(PascalContextDataset59, self).__init__( - img_suffix='.jpg', - seg_map_suffix='.png', - split=split, - reduce_zero_label=True, - **kwargs) - assert osp.exists(self.img_dir) and self.split is not None diff --git a/spaces/gligen/demo/gligen/ldm/models/diffusion/ldm.py b/spaces/gligen/demo/gligen/ldm/models/diffusion/ldm.py deleted file mode 100644 index 78fa65862d848a3fa49ff8c2b7bc475067175891..0000000000000000000000000000000000000000 --- a/spaces/gligen/demo/gligen/ldm/models/diffusion/ldm.py +++ /dev/null @@ -1,88 +0,0 @@ -import torch -import torch.nn as nn -import numpy as np -from tqdm import tqdm -from ldm.util import default -from ldm.modules.diffusionmodules.util import extract_into_tensor -from .ddpm import DDPM - - - -class LatentDiffusion(DDPM): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - # hardcoded - self.clip_denoised = False - - - - def q_sample(self, x_start, t, noise=None): - noise = default(noise, lambda: torch.randn_like(x_start)) - return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) - - - "Does not support DDPM sampling anymore. Only do DDIM or PLMS" - - # = = = = = = = = = = = = Below is for sampling = = = = = = = = = = = = # - - # def predict_start_from_noise(self, x_t, t, noise): - # return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - - # extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) - - # def q_posterior(self, x_start, x_t, t): - # posterior_mean = ( - # extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + - # extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t - # ) - # posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) - # posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) - # return posterior_mean, posterior_variance, posterior_log_variance_clipped - - - # def p_mean_variance(self, model, x, c, t): - - # model_out = model(x, t, c) - # x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) - - # if self.clip_denoised: - # x_recon.clamp_(-1., 1.) - - # model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) - # return model_mean, posterior_variance, posterior_log_variance, x_recon - - - # @torch.no_grad() - # def p_sample(self, model, x, c, t): - # b, *_, device = *x.shape, x.device - # model_mean, _, model_log_variance, x0 = self.p_mean_variance(model, x=x, c=c, t=t, ) - # noise = torch.randn_like(x) - - # # no noise when t == 0 - # nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) - - # return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0 - - - # @torch.no_grad() - # def p_sample_loop(self, model, shape, c): - # device = self.betas.device - # b = shape[0] - # img = torch.randn(shape, device=device) - - # iterator = tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps) - # for i in iterator: - # ts = torch.full((b,), i, device=device, dtype=torch.long) - # img, x0 = self.p_sample(model, img, c, ts) - - # return img - - - # @torch.no_grad() - # def sample(self, model, shape, c, uc=None, guidance_scale=None): - # return self.p_sample_loop(model, shape, c) - - - - - diff --git a/spaces/gradio-tests/Image_Upscaling_Restoration_Colorization/app.py b/spaces/gradio-tests/Image_Upscaling_Restoration_Colorization/app.py deleted file mode 100644 index 5d011a75bb7c05b2710954ce49bb98976270eb60..0000000000000000000000000000000000000000 --- a/spaces/gradio-tests/Image_Upscaling_Restoration_Colorization/app.py +++ /dev/null @@ -1,100 +0,0 @@ -import os, pathlib -import cv2 -import gradio as gr -import torch -from basicsr.archs.srvgg_arch import SRVGGNetCompact -from gfpgan.utils import GFPGANer -from realesrgan.utils import RealESRGANer -os.system("hub install deoldify==1.0.1") -import paddlehub as hub -os.system("pip freeze") - - -# download weights -if not os.path.exists('GFPGANv1.4.pth'): - os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P .") - -model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu') -model_path = 'realesr-general-x4v3.pth' -half = True if torch.cuda.is_available() else False -upsampler = RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half) - -os.makedirs('output', exist_ok=True) - -colorizer = hub.Module(name='deoldify') -render_factor=5 - -def colorize_image(image): - color_image = colorizer.predict(image) - return color_image - - -def inference(img, scale): - print(img, scale) - try: - extension = os.path.splitext(os.path.basename(str(img)))[1] - img = cv2.imread(img, cv2.IMREAD_UNCHANGED) - if len(img.shape) == 3 and img.shape[2] == 4: - img_mode = 'RGBA' - elif len(img.shape) == 2: # for gray inputs - img_mode = None - img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) - else: - img_mode = None - - h, w = img.shape[0:2] - if h < 300: - img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4) - face_enhancer = GFPGANer(model_path='GFPGANv1.4.pth', upscale=2, arch='clean', channel_multiplier=2, bg_upsampler=upsampler) - try: - # _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True, weight=weight) - _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) - except RuntimeError as error: - print('Error', error) - - try: - if scale != 2: - interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS4 - h, w = img.shape[0:2] - output = cv2.resize(output, (int(w * scale / 2), int(h * scale / 2)), interpolation=interpolation) - except Exception as error: - print('wrong scale input.', error) - if img_mode == 'RGBA': # RGBA images should be saved in png format - extension = 'png' - else: - extension = 'jpg' - save_path = f'output/out.{extension}' - output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) - cv2.imwrite(save_path, output) - print('upsampled image!') - output_img = colorize_image(save_path) - outputim = output_img[1] - print(type(outputim)) - print('colorized image!') - return pathlib.Path(outputim) - except Exception as error: - print('global exception', error) - return None, None - - - -with gr.Blocks() as demo: - gr.Markdown("# Image Upscaling, Restoration and Colorization") - gr.Markdown("## Choose an upscaling factor below and colorize your image!") - with gr.Row(): - with gr.Column(): - in_image = gr.inputs.Image(type="filepath", label="Input") - factor = gr.Slider(2, 10, value=2, step = 1, label="Rescaling factor") - #gr.inputs.Number(, default=2) - btn = gr.Button("Upscale and Colorize!") - with gr.Column(): - gallery = gr.Image() - #out_image = gr.outputs.Image(type="numpy", label="Output (The whole image)") - #dld = gr.outputs.File(label="Download the output image") - btn.click(fn=inference, inputs=[in_image,factor], outputs=gallery) - - - gr.Markdown("Try different upsampling values to see which gives the best colorized output!") - gr.Markdown("If the connection errors out, try a smaller upsampling value.") - -demo.launch() \ No newline at end of file diff --git a/spaces/gradio/HuBERT/examples/cross_lingual_language_model/README.md b/spaces/gradio/HuBERT/examples/cross_lingual_language_model/README.md deleted file mode 100644 index af9128e39e5925e9411d162c2f24a19e4532d618..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/examples/cross_lingual_language_model/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# Cross-Lingual Language Model Pre-training - -Below are some details for training Cross-Lingual Language Models (XLM) - similar to the ones presented in [Lample & Conneau, 2019](https://arxiv.org/pdf/1901.07291.pdf) - in Fairseq. The current implementation only supports the Masked Language Model (MLM) from the paper above. - -## Downloading and Tokenizing Monolingual Data - -Pointers to the monolingual data from wikipedia, used for training the XLM-style MLM model as well as details on processing (tokenization and BPE) it can be found in the [XLM Github Repository](https://github.com/facebookresearch/XLM#download--preprocess-monolingual-data). - -Let's assume the following for the code snippets in later sections to work -- Processed data is in the folder: monolingual_data/processed -- Each language has 3 files for train, test and validation. For example we have the following files for English: - train.en, valid.en -- We are training a model for 5 languages: Arabic (ar), German (de), English (en), Hindi (hi) and French (fr) -- The vocabulary file is monolingual_data/processed/vocab_mlm - - -## Fairseq Pre-processing and Binarization - -Pre-process and binarize the data with the MaskedLMDictionary and cross_lingual_lm task - -```bash -# Ensure the output directory exists -DATA_DIR=monolingual_data/fairseq_processed -mkdir -p "$DATA_DIR" - -for lg in ar de en hi fr -do - - fairseq-preprocess \ - --task cross_lingual_lm \ - --srcdict monolingual_data/processed/vocab_mlm \ - --only-source \ - --trainpref monolingual_data/processed/train \ - --validpref monolingual_data/processed/valid \ - --testpref monolingual_data/processed/test \ - --destdir monolingual_data/fairseq_processed \ - --workers 20 \ - --source-lang $lg - - # Since we only have a source language, the output file has a None for the - # target language. Remove this - - for stage in train test valid - - sudo mv "$DATA_DIR/$stage.$lg-None.$lg.bin" "$stage.$lg.bin" - sudo mv "$DATA_DIR/$stage.$lg-None.$lg.idx" "$stage.$lg.idx" - - done - -done -``` - -## Train a Cross-lingual Language Model similar to the XLM MLM model - -Use the following command to train the model on 5 languages. - -``` -fairseq-train \ ---task cross_lingual_lm monolingual_data/fairseq_processed \ ---save-dir checkpoints/mlm \ ---max-update 2400000 --save-interval 1 --no-epoch-checkpoints \ ---arch xlm_base \ ---optimizer adam --lr-scheduler reduce_lr_on_plateau \ ---lr-shrink 0.5 --lr 0.0001 --stop-min-lr 1e-09 \ ---dropout 0.1 \ ---criterion legacy_masked_lm_loss \ ---max-tokens 2048 --tokens-per-sample 256 --attention-dropout 0.1 \ ---dataset-impl lazy --seed 0 \ ---masked-lm-only \ ---monolingual-langs 'ar,de,en,hi,fr' --num-segment 5 \ ---ddp-backend=legacy_ddp -``` - -Some Notes: -- Using tokens_per_sample greater than 256 can cause OOM (out-of-memory) issues. Usually since MLM packs in streams of text, this parameter doesn't need much tuning. -- The Evaluation workflow for computing MLM Perplexity on test data is in progress. -- Finetuning this model on a downstream task is something which is not currently available. diff --git a/spaces/gradio/hello_blocks/run.py b/spaces/gradio/hello_blocks/run.py deleted file mode 100644 index f11bca19f42a7ffaeb0567874ee15507401cbfba..0000000000000000000000000000000000000000 --- a/spaces/gradio/hello_blocks/run.py +++ /dev/null @@ -1,15 +0,0 @@ -import gradio as gr - - -def greet(name): - return "Hello " + name + "!" - - -with gr.Blocks() as demo: - name = gr.Textbox(label="Name") - output = gr.Textbox(label="Output Box") - greet_btn = gr.Button("Greet") - greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet") - -if __name__ == "__main__": - demo.launch() diff --git a/spaces/h2oai/wave-tour/examples/persona.py b/spaces/h2oai/wave-tour/examples/persona.py deleted file mode 100644 index 16ea0848ed9ce1eac94196a06d88328f33a33d73..0000000000000000000000000000000000000000 --- a/spaces/h2oai/wave-tour/examples/persona.py +++ /dev/null @@ -1,27 +0,0 @@ -# Form / Persona -# Create an individual's persona or avatar, a visual representation of a person across products. -# #form -# --- -from h2o_wave import main, app, Q, ui - - -@app('/demo') -async def serve(q: Q): - if q.args.persona: - q.page['example'].items = [ - ui.text_m(f'q.args.persona={q.args.persona}'), - ui.button(name='back', label='Back', primary=True), - ] - else: - image = 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&h=750&w=1260' - q.page['example'] = ui.form_card(box='1 1 2 7', items=[ - ui.persona(title='John Doe', subtitle='Data Scientist', caption='Online', size='xs', image=image), - ui.persona(title='John Doe', subtitle='Data Scientist', caption='Online', size='s', image=image), - ui.persona(title='John Doe', subtitle='Data Scientist', caption='Online', size='m', image=image), - ui.persona(title='John Doe', subtitle='Data Scientist', caption='Online', size='l', image=image), - ui.persona(title='John Doe', subtitle='Data Scientist', caption='Online', size='xl', image=image), - ui.persona(title='', initials='JD', initials_color='$grey'), - ui.persona(name='persona', title='Click me', size='s', image=image) - ]) - - await q.page.save() diff --git a/spaces/hamelcubsfan/AutoGPT/tests.py b/spaces/hamelcubsfan/AutoGPT/tests.py deleted file mode 100644 index 62f76da8ac4925ef6cdfcce0484612cf70959862..0000000000000000000000000000000000000000 --- a/spaces/hamelcubsfan/AutoGPT/tests.py +++ /dev/null @@ -1,21 +0,0 @@ -import unittest - -import coverage - -if __name__ == "__main__": - # Start coverage collection - cov = coverage.Coverage() - cov.start() - - # Load all tests from the 'autogpt/tests' package - suite = unittest.defaultTestLoader.discover("./tests") - - # Run the tests - unittest.TextTestRunner().run(suite) - - # Stop coverage collection - cov.stop() - cov.save() - - # Report the coverage - cov.report(show_missing=True) diff --git a/spaces/hanhanbeea/anime-aesthetic-predict/app.py b/spaces/hanhanbeea/anime-aesthetic-predict/app.py deleted file mode 100644 index 6f0cd457993cc220641a974f27509b94fcace949..0000000000000000000000000000000000000000 --- a/spaces/hanhanbeea/anime-aesthetic-predict/app.py +++ /dev/null @@ -1,28 +0,0 @@ -import cv2 -import numpy as np -import gradio as gr -import onnxruntime as rt -from huggingface_hub import hf_hub_download - - -def predict(img): - img = img.astype(np.float32) / 255 - s = 768 - h, w = img.shape[:-1] - h, w = (s, int(s * w / h)) if h > w else (int(s * h / w), s) - ph, pw = s - h, s - w - img_input = np.zeros([s, s, 3], dtype=np.float32) - img_input[ph // 2:ph // 2 + h, pw // 2:pw // 2 + w] = cv2.resize(img, (w, h)) - img_input = np.transpose(img_input, (2, 0, 1)) - img_input = img_input[np.newaxis, :] - pred = model.run(None, {"img": img_input})[0].item() - return pred - - -if __name__ == "__main__": - model_path = hf_hub_download(repo_id="skytnt/anime-aesthetic", filename="model.onnx") - model = rt.InferenceSession(model_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) - examples = [[f"examples/{x:02d}.jpg"] for x in range(0, 2)] - app = gr.Interface(predict, gr.Image(label="input image"), gr.Number(label="score"),title="Anime Aesthetic Predict", - allow_flagging="never", examples=examples, cache_examples=False) - app.launch() diff --git a/spaces/hanzportgas/rvc-models/infer_pack/models.py b/spaces/hanzportgas/rvc-models/infer_pack/models.py deleted file mode 100644 index 96165f73644e6fb92d0ffedb4a3c9e1a457cb989..0000000000000000000000000000000000000000 --- a/spaces/hanzportgas/rvc-models/infer_pack/models.py +++ /dev/null @@ -1,982 +0,0 @@ -import math, pdb, os -from time import time as ttime -import torch -from torch import nn -from torch.nn import functional as F -from infer_pack import modules -from infer_pack import attentions -from infer_pack import commons -from infer_pack.commons import init_weights, get_padding -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from infer_pack.commons import init_weights -import numpy as np -from infer_pack import commons - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder256Sim(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - x = self.proj(x) * x_mask - return x, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMs256NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs256NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs256NSFsid_sim(nn.Module): - """ - Synthesizer for Training - """ - - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - # hop_length, - gin_channels=0, - use_sdp=True, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256Sim( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - is_half=kwargs["is_half"], - ) - - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y_lengths, ds - ): # y是spec不需要了现在 - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - x, x_mask = self.enc_p(phone, pitch, phone_lengths) - x = self.flow(x, x_mask, g=g, reverse=True) - z_slice, ids_slice = commons.rand_slice_segments( - x, y_lengths, self.segment_size - ) - - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice - - def infer( - self, phone, phone_lengths, pitch, pitchf, ds, max_len=None - ): # y是spec不需要了现在 - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - x, x_mask = self.enc_p(phone, pitch, phone_lengths) - x = self.flow(x, x_mask, g=g, reverse=True) - o = self.dec((x * x_mask)[:, :, :max_len], pitchf, g=g) - return o, o - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/hbui/RegBot-Chat-with-Docs/README.md b/spaces/hbui/RegBot-Chat-with-Docs/README.md deleted file mode 100644 index d39649259f124707bc17f13b7da37d1e03df9a45..0000000000000000000000000000000000000000 --- a/spaces/hbui/RegBot-Chat-with-Docs/README.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Chat with Docs -emoji: 🦙 -license: mit -sdk: streamlit -python_version: 3.9 -app_file: app.py -colorFrom: pink -colorTo: blue -pinned: false -duplicated_from: ashrma/Chat-with-Docs ---- -# Chat-with-Docs - -![image](https://user-images.githubusercontent.com/26565263/236671146-5fc5d5f0-4acb-40c7-9d9a-dc072efd8078.png) - -Chat with your Docs and gain better insights. Powered by `LlamaIndex` and `Streamlit` is used for UI. -Handles `CSV/PDFs/Txt/Doc`. CSV file is catered via [PandasAI](https://llamahub.ai/l/pandas_ai) loader and rest of the docs are handled via -`GPTVectorStoreIndex`. - -Clone the repo or copy the `.py ` file in your local machine. - -## Install required Dependencies -``` -pip install -r requirements.txt -``` - -## Create a folder in the root dir and name it as `documents` - -## Run the application -`streamlit run chat_with_docs.py` - -## How to Contribute -Feel free to open any Issue or PR request. This small application can help anyone to interact with their docs more smartly in just 2-3 steps. - -## Roadmap -- [ ] Add support for choosing in between GPT-3/GPT-3.5/GPT-4 or HuggingFace model for creating vectors and generating rich responses. -- [x] Blog explaining the entire application in detail. -- [ ] Add Docker support. -- [ ] Deploy the project on Streamlit or DataButton platform. -- [ ] Add support to handle multiple files at once. - -## Snapshots -- Upload a CSV file. Get better insights by just asking question, Render graphs based on the Data -![image](https://user-images.githubusercontent.com/26565263/236671237-8517eecd-59f5-4961-8e33-772a26e92962.png) -![image](https://user-images.githubusercontent.com/26565263/236671280-e5e9da7a-dd32-4af2-bd79-42545ad67d07.png) -![image](https://user-images.githubusercontent.com/26565263/236671344-31967a79-2601-4cf2-bb2e-12a9eaf9429d.png) - -- In Doc section, Upload PDFs/Txt/Docs to chat with your docs directly. No need to press `CTRL+F` to search for anything in the Docs -![image](https://user-images.githubusercontent.com/26565263/236671378-650d387f-57ad-4738-9bd0-15229f7e2e1d.png) -![image](https://user-images.githubusercontent.com/26565263/236671580-0b032941-6c89-430a-a42c-f68655d39f71.png) \ No newline at end of file diff --git a/spaces/hebert2099/MusicGen/CHANGELOG.md b/spaces/hebert2099/MusicGen/CHANGELOG.md deleted file mode 100644 index a685bcae80d0c64e64f5f51a9b9aa9245cec4b9e..0000000000000000000000000000000000000000 --- a/spaces/hebert2099/MusicGen/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - -## [0.0.1a] - TBD - -Initial release, with model evaluation only. \ No newline at end of file diff --git a/spaces/heiyubili/bingo/src/components/ui/codeblock.tsx b/spaces/heiyubili/bingo/src/components/ui/codeblock.tsx deleted file mode 100644 index aabda4e3b59f4e36b6ab79feb19d8d18b70e881b..0000000000000000000000000000000000000000 --- a/spaces/heiyubili/bingo/src/components/ui/codeblock.tsx +++ /dev/null @@ -1,142 +0,0 @@ -'use client' - -import { FC, memo } from 'react' -import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter' -import { coldarkDark } from 'react-syntax-highlighter/dist/cjs/styles/prism' - -import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard' -import { IconCheck, IconCopy, IconDownload } from '@/components/ui/icons' -import { Button } from '@/components/ui/button' - -interface Props { - language: string - value: string -} - -interface languageMap { - [key: string]: string | undefined -} - -export const programmingLanguages: languageMap = { - javascript: '.js', - python: '.py', - java: '.java', - c: '.c', - cpp: '.cpp', - 'c++': '.cpp', - 'c#': '.cs', - ruby: '.rb', - php: '.php', - swift: '.swift', - 'objective-c': '.m', - kotlin: '.kt', - typescript: '.ts', - go: '.go', - perl: '.pl', - rust: '.rs', - scala: '.scala', - haskell: '.hs', - lua: '.lua', - shell: '.sh', - sql: '.sql', - html: '.html', - css: '.css' - // add more file extensions here, make sure the key is same as language prop in CodeBlock.tsx component -} - -export const generateRandomString = (length: number, lowercase = false) => { - const chars = 'ABCDEFGHJKLMNPQRSTUVWXY3456789' // excluding similar looking characters like Z, 2, I, 1, O, 0 - let result = '' - for (let i = 0; i < length; i++) { - result += chars.charAt(Math.floor(Math.random() * chars.length)) - } - return lowercase ? result.toLowerCase() : result -} - -const CodeBlock: FC = memo(({ language, value }) => { - const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 }) - - const downloadAsFile = () => { - if (typeof window === 'undefined') { - return - } - const fileExtension = programmingLanguages[language] || '.file' - const suggestedFileName = `file-${generateRandomString( - 3, - true - )}${fileExtension}` - const fileName = window.prompt('Enter file name' || '', suggestedFileName) - - if (!fileName) { - // User pressed cancel on prompt. - return - } - - const blob = new Blob([value], { type: 'text/plain' }) - const url = URL.createObjectURL(blob) - const link = document.createElement('a') - link.download = fileName - link.href = url - link.style.display = 'none' - document.body.appendChild(link) - link.click() - document.body.removeChild(link) - URL.revokeObjectURL(url) - } - - const onCopy = () => { - if (isCopied) return - copyToClipboard(value) - } - - return ( -
    -
    - {language} -
    - - -
    -
    - - {value} - -
    - ) -}) -CodeBlock.displayName = 'CodeBlock' - -export { CodeBlock } diff --git a/spaces/hf4all/chatgpt-next-web-bing/Dockerfile b/spaces/hf4all/chatgpt-next-web-bing/Dockerfile deleted file mode 100644 index 0bf993847550f9b292ce0dcb720c3a722b950a06..0000000000000000000000000000000000000000 --- a/spaces/hf4all/chatgpt-next-web-bing/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM node:18 -RUN git clone https://github.com/Yidadaa/ChatGPT-Next-Web.git -WORKDIR "ChatGPT-Next-Web" -RUN npm i -RUN npm run build -EXPOSE 3000 -CMD ["npm", "run", "start"] \ No newline at end of file diff --git a/spaces/hhalim/DAvaViz-graph/README.md b/spaces/hhalim/DAvaViz-graph/README.md deleted file mode 100644 index f9df699a7def5a64fcd29d1c4c2403cd56d0238c..0000000000000000000000000000000000000000 --- a/spaces/hhalim/DAvaViz-graph/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 07 GraphViz PyDeck Map AIUIUX Demo -emoji: 🕸️📊 -colorFrom: green -colorTo: red -sdk: streamlit -sdk_version: 1.10.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/ho11laqe/nnUNet_calvingfront_detection/nnunet/network_architecture/generic_UNet_MTLlate_boundary.py b/spaces/ho11laqe/nnUNet_calvingfront_detection/nnunet/network_architecture/generic_UNet_MTLlate_boundary.py deleted file mode 100644 index 28995ee6272c397f3504e0c9aa01c46ee3270ff1..0000000000000000000000000000000000000000 --- a/spaces/ho11laqe/nnUNet_calvingfront_detection/nnunet/network_architecture/generic_UNet_MTLlate_boundary.py +++ /dev/null @@ -1,464 +0,0 @@ -# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from copy import deepcopy -from nnunet.utilities.nd_softmax import softmax_helper -from torch import nn -import torch -import numpy as np -from nnunet.network_architecture.initialization import InitWeights_He -from nnunet.network_architecture.neural_network import SegmentationNetwork -import torch.nn.functional -import matplotlib -import matplotlib.pyplot as plt - - -class ConvDropoutNormNonlin(nn.Module): - """ - fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad. - """ - - def __init__(self, input_channels, output_channels, - conv_op=nn.Conv2d, conv_kwargs=None, - norm_op=nn.BatchNorm2d, norm_op_kwargs=None, - dropout_op=nn.Dropout2d, dropout_op_kwargs=None, - nonlin=nn.LeakyReLU, nonlin_kwargs=None): - super(ConvDropoutNormNonlin, self).__init__() - if nonlin_kwargs is None: - nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} - if dropout_op_kwargs is None: - dropout_op_kwargs = {'p': 0.5, 'inplace': True} - if norm_op_kwargs is None: - norm_op_kwargs = {'eps': 1e-5, 'affine': True, 'momentum': 0.1} - if conv_kwargs is None: - conv_kwargs = {'kernel_size': 3, 'stride': 1, 'padding': 1, 'dilation': 1, 'bias': True} - - self.nonlin_kwargs = nonlin_kwargs - self.nonlin = nonlin - self.dropout_op = dropout_op - self.dropout_op_kwargs = dropout_op_kwargs - self.norm_op_kwargs = norm_op_kwargs - self.conv_kwargs = conv_kwargs - self.conv_op = conv_op - self.norm_op = norm_op - - self.conv = self.conv_op(input_channels, output_channels, **self.conv_kwargs) - if self.dropout_op is not None and self.dropout_op_kwargs['p'] is not None and self.dropout_op_kwargs[ - 'p'] > 0: - self.dropout = self.dropout_op(**self.dropout_op_kwargs) - else: - self.dropout = None - self.instnorm = self.norm_op(output_channels, **self.norm_op_kwargs) - self.lrelu = self.nonlin(**self.nonlin_kwargs) - - def forward(self, x): - x = self.conv(x) - if self.dropout is not None: - x = self.dropout(x) - return self.lrelu(self.instnorm(x)) - - -class ConvDropoutNonlinNorm(ConvDropoutNormNonlin): - def forward(self, x): - x = self.conv(x) - if self.dropout is not None: - x = self.dropout(x) - return self.instnorm(self.lrelu(x)) - - -class StackedConvLayers(nn.Module): - def __init__(self, input_feature_channels, output_feature_channels, num_convs, - conv_op=nn.Conv2d, conv_kwargs=None, - norm_op=nn.BatchNorm2d, norm_op_kwargs=None, - dropout_op=nn.Dropout2d, dropout_op_kwargs=None, - nonlin=nn.LeakyReLU, nonlin_kwargs=None, first_stride=None, basic_block=ConvDropoutNormNonlin): - ''' - stacks ConvDropoutNormLReLU layers. initial_stride will only be applied to first layer in the stack. The other - parameters affect all layers - :param input_feature_channels: - :param output_feature_channels: - :param num_convs: - :param dilation: - :param kernel_size: - :param padding: - :param dropout: - :param initial_stride: - :param conv_op: - :param norm_op: - :param dropout_op: - :param inplace: - :param neg_slope: - :param norm_affine: - :param conv_bias: - ''' - self.input_channels = input_feature_channels - self.output_channels = output_feature_channels - - if nonlin_kwargs is None: - nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} - if dropout_op_kwargs is None: - dropout_op_kwargs = {'p': 0.5, 'inplace': True} - if norm_op_kwargs is None: - norm_op_kwargs = {'eps': 1e-5, 'affine': True, 'momentum': 0.1} - if conv_kwargs is None: - conv_kwargs = {'kernel_size': 3, 'stride': 1, 'padding': 1, 'dilation': 1, 'bias': True} - - self.nonlin_kwargs = nonlin_kwargs - self.nonlin = nonlin - self.dropout_op = dropout_op - self.dropout_op_kwargs = dropout_op_kwargs - self.norm_op_kwargs = norm_op_kwargs - self.conv_kwargs = conv_kwargs - self.conv_op = conv_op - self.norm_op = norm_op - - if first_stride is not None: - self.conv_kwargs_first_conv = deepcopy(conv_kwargs) - self.conv_kwargs_first_conv['stride'] = first_stride - else: - self.conv_kwargs_first_conv = conv_kwargs - - super(StackedConvLayers, self).__init__() - self.blocks = nn.Sequential( - *([basic_block(input_feature_channels, output_feature_channels, self.conv_op, - self.conv_kwargs_first_conv, - self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, - self.nonlin, self.nonlin_kwargs)] + - [basic_block(output_feature_channels, output_feature_channels, self.conv_op, - self.conv_kwargs, - self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, - self.nonlin, self.nonlin_kwargs) for _ in range(num_convs - 1)])) - - def forward(self, x): - return self.blocks(x) - - -def print_module_training_status(module): - if isinstance(module, nn.Conv2d) or isinstance(module, nn.Conv3d) or isinstance(module, nn.Dropout3d) or \ - isinstance(module, nn.Dropout2d) or isinstance(module, nn.Dropout) or isinstance(module, nn.InstanceNorm3d) \ - or isinstance(module, nn.InstanceNorm2d) or isinstance(module, nn.InstanceNorm1d) \ - or isinstance(module, nn.BatchNorm2d) or isinstance(module, nn.BatchNorm3d) or isinstance(module, - nn.BatchNorm1d): - print(str(module), module.training) - - -class Upsample(nn.Module): - def __init__(self, size=None, scale_factor=None, mode='nearest', align_corners=False): - super(Upsample, self).__init__() - self.align_corners = align_corners - self.mode = mode - self.scale_factor = scale_factor - self.size = size - - def forward(self, x): - return nn.functional.interpolate(x, size=self.size, scale_factor=self.scale_factor, mode=self.mode, - align_corners=self.align_corners) - - -class Generic_UNet_MTLlate_boundary(SegmentationNetwork): - DEFAULT_BATCH_SIZE_3D = 2 - DEFAULT_PATCH_SIZE_3D = (64, 192, 160) - SPACING_FACTOR_BETWEEN_STAGES = 2 - BASE_NUM_FEATURES_3D = 30 - MAX_NUMPOOL_3D = 999 - MAX_NUM_FILTERS_3D = 320 - - DEFAULT_PATCH_SIZE_2D = (256, 256) - BASE_NUM_FEATURES_2D = 30 - DEFAULT_BATCH_SIZE_2D = 50 - MAX_NUMPOOL_2D = 999 - MAX_FILTERS_2D = 480 - - use_this_for_batch_size_computation_2D = 19739648 - use_this_for_batch_size_computation_3D = 520000000 # 505789440 - - def __init__(self, input_channels, base_num_features, num_classes, num_pool, num_conv_per_stage=2, - feat_map_mul_on_downscale=2, conv_op=nn.Conv2d, - norm_op=nn.BatchNorm2d, norm_op_kwargs=None, - dropout_op=nn.Dropout2d, dropout_op_kwargs=None, - nonlin=nn.LeakyReLU, nonlin_kwargs=None, deep_supervision=True, dropout_in_localization=False, - final_nonlin=softmax_helper, weightInitializer=InitWeights_He(1e-2), pool_op_kernel_sizes=None, - conv_kernel_sizes=None, - upscale_logits=False, convolutional_pooling=False, convolutional_upsampling=False, - max_num_features=None, basic_block=ConvDropoutNormNonlin, - seg_output_use_bias=False): - """ - basically more flexible than v1, architecture is the same - - Does this look complicated? Nah bro. Functionality > usability - - This does everything you need, including world peace. - - Questions? -> f.isensee@dkfz.de - """ - super(Generic_UNet_MTLlate_boundary, self).__init__() - self.convolutional_upsampling = convolutional_upsampling - self.convolutional_pooling = convolutional_pooling - self.upscale_logits = upscale_logits - if nonlin_kwargs is None: - nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} - if dropout_op_kwargs is None: - dropout_op_kwargs = {'p': 0.5, 'inplace': True} - if norm_op_kwargs is None: - norm_op_kwargs = {'eps': 1e-5, 'affine': True, 'momentum': 0.1} - - self.conv_kwargs = {'stride': 1, 'dilation': 1, 'bias': True} - - self.nonlin = nonlin - self.nonlin_kwargs = nonlin_kwargs - self.dropout_op_kwargs = dropout_op_kwargs - self.norm_op_kwargs = norm_op_kwargs - self.weightInitializer = weightInitializer - self.conv_op = conv_op - self.norm_op = norm_op - self.dropout_op = dropout_op - self.num_classes = num_classes - self.final_nonlin = final_nonlin - self._deep_supervision = deep_supervision - self.do_ds = deep_supervision - - if conv_op == nn.Conv2d: - upsample_mode = 'bilinear' - pool_op = nn.MaxPool2d - transpconv = nn.ConvTranspose2d - if pool_op_kernel_sizes is None: - pool_op_kernel_sizes = [(2, 2)] * num_pool - if conv_kernel_sizes is None: - conv_kernel_sizes = [(3, 3)] * (num_pool + 1) - elif conv_op == nn.Conv3d: - upsample_mode = 'trilinear' - pool_op = nn.MaxPool3d - transpconv = nn.ConvTranspose3d - if pool_op_kernel_sizes is None: - pool_op_kernel_sizes = [(2, 2, 2)] * num_pool - if conv_kernel_sizes is None: - conv_kernel_sizes = [(3, 3, 3)] * (num_pool + 1) - else: - raise ValueError("unknown convolution dimensionality, conv op: %s" % str(conv_op)) - - self.input_shape_must_be_divisible_by = np.prod(pool_op_kernel_sizes, 0, dtype=np.int64) - self.pool_op_kernel_sizes = pool_op_kernel_sizes - self.conv_kernel_sizes = conv_kernel_sizes - - self.conv_pad_sizes = [] - for krnl in self.conv_kernel_sizes: - self.conv_pad_sizes.append([1 if i == 3 else 0 for i in krnl]) - - if max_num_features is None: - if self.conv_op == nn.Conv3d: - self.max_num_features = self.MAX_NUM_FILTERS_3D - else: - self.max_num_features = self.MAX_FILTERS_2D - else: - self.max_num_features = max_num_features - - self.conv_blocks_context = [] - self.conv_blocks_localization_1 = [] - self.conv_blocks_localization_2 = [] - self.td = [] - self.tu_1 = [] - self.tu_2 = [] - self.seg_outputs_1 = [] - self.seg_outputs_2 = [] - - output_features = base_num_features - input_features = input_channels - - for d in range(num_pool): - # determine the first stride - if d != 0 and self.convolutional_pooling: - first_stride = pool_op_kernel_sizes[d - 1] - else: - first_stride = None - - self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[d] - self.conv_kwargs['padding'] = self.conv_pad_sizes[d] - # add convolutions - self.conv_blocks_context.append(StackedConvLayers(input_features, output_features, num_conv_per_stage, - self.conv_op, self.conv_kwargs, self.norm_op, - self.norm_op_kwargs, self.dropout_op, - self.dropout_op_kwargs, self.nonlin, self.nonlin_kwargs, - first_stride, basic_block=basic_block)) - if not self.convolutional_pooling: - self.td.append(pool_op(pool_op_kernel_sizes[d])) - input_features = output_features - output_features = int(np.round(output_features * feat_map_mul_on_downscale)) - - output_features = min(output_features, self.max_num_features) - - # now the bottleneck. - # determine the first stride - if self.convolutional_pooling: - first_stride = pool_op_kernel_sizes[-1] - else: - first_stride = None - - # the output of the last conv must match the number of features from the skip connection if we are not using - # convolutional upsampling. If we use convolutional upsampling then the reduction in feature maps will be - # done by the transposed conv - if self.convolutional_upsampling: - final_num_features = output_features - else: - final_num_features = self.conv_blocks_context[-1].output_channels - - self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[num_pool] - self.conv_kwargs['padding'] = self.conv_pad_sizes[num_pool] - self.conv_blocks_context.append(nn.Sequential( - StackedConvLayers(input_features, output_features, num_conv_per_stage - 1, self.conv_op, self.conv_kwargs, - self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, self.nonlin, - self.nonlin_kwargs, first_stride, basic_block=basic_block), - StackedConvLayers(output_features, final_num_features, 1, self.conv_op, self.conv_kwargs, - self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, self.nonlin, - self.nonlin_kwargs, basic_block=basic_block))) - - # if we don't want to do dropout in the localization pathway then we set the dropout prob to zero here - if not dropout_in_localization: - old_dropout_p = self.dropout_op_kwargs['p'] - self.dropout_op_kwargs['p'] = 0.0 - - # now lets build the localization pathway - for u in range(num_pool): - nfeatures_from_down = final_num_features - nfeatures_from_skip = self.conv_blocks_context[ - -(2 + u)].output_channels # self.conv_blocks_context[-1] is bottleneck, so start with -2 - n_features_after_tu_and_concat = nfeatures_from_skip * 2 - - # the first conv reduces the number of features to match those of skip - # the following convs work on that number of features - # if not convolutional upsampling then the final conv reduces the num of features again - if u != num_pool - 1 and not self.convolutional_upsampling: - final_num_features = self.conv_blocks_context[-(3 + u)].output_channels - else: - final_num_features = nfeatures_from_skip - - if not self.convolutional_upsampling: - self.tu_1.append(Upsample(scale_factor=pool_op_kernel_sizes[-(u + 1)], mode=upsample_mode)) - else: - self.tu_1.append(transpconv(nfeatures_from_down, nfeatures_from_skip, pool_op_kernel_sizes[-(u + 1)], - pool_op_kernel_sizes[-(u + 1)], bias=False)) - - - self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[- (u + 1)] - self.conv_kwargs['padding'] = self.conv_pad_sizes[- (u + 1)] - self.conv_blocks_localization_1.append(nn.Sequential( - StackedConvLayers(n_features_after_tu_and_concat, nfeatures_from_skip, num_conv_per_stage - 1, - self.conv_op, self.conv_kwargs, self.norm_op, self.norm_op_kwargs, self.dropout_op, - self.dropout_op_kwargs, self.nonlin, self.nonlin_kwargs, basic_block=basic_block), - StackedConvLayers(nfeatures_from_skip, final_num_features, 1, self.conv_op, self.conv_kwargs, - self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, - self.nonlin, self.nonlin_kwargs, basic_block=basic_block) - )) - - - for ds in range(len(self.conv_blocks_localization_1)): - self.seg_outputs_1.append(conv_op(self.conv_blocks_localization_1[ds][-1].output_channels, num_classes[0]+num_classes[1]+num_classes[2], - 1, 1, 0, 1, 1, seg_output_use_bias)) - - - - self.upscale_logits_ops = [] - cum_upsample = np.cumprod(np.vstack(pool_op_kernel_sizes), axis=0)[::-1] - for usl in range(num_pool - 1): - if self.upscale_logits: - self.upscale_logits_ops.append(Upsample(scale_factor=tuple([int(i) for i in cum_upsample[usl + 1]]), - mode=upsample_mode)) - else: - self.upscale_logits_ops.append(lambda x: x) - - if not dropout_in_localization: - self.dropout_op_kwargs['p'] = old_dropout_p - - # register all modules properly - self.conv_blocks_context = nn.ModuleList(self.conv_blocks_context) - - self.conv_blocks_localization_1 = nn.ModuleList(self.conv_blocks_localization_1) - - self.td = nn.ModuleList(self.td) - self.tu_1 = nn.ModuleList(self.tu_1) - self.seg_outputs_1 = nn.ModuleList(self.seg_outputs_1) - - if self.upscale_logits: - self.upscale_logits_ops = nn.ModuleList( - self.upscale_logits_ops) # lambda x:x is not a Module so we need to distinguish here - - if self.weightInitializer is not None: - self.apply(self.weightInitializer) - # self.apply(print_module_training_status) - - def forward(self, x): - skips = [] - seg_outputs = [] - for d in range(len(self.conv_blocks_context) - 1): - x = self.conv_blocks_context[d](x) - skips.append(x) - if not self.convolutional_pooling: - x = self.td[d](x) - - x1 = self.conv_blocks_context[-1](x) - - # Decoder 1 - for u in range(len(self.tu_1)): - x1 = self.tu_1[u](x1) - x1 = torch.cat((x1, skips[-(u + 1)]), dim=1) - x1 = self.conv_blocks_localization_1[u](x1) - seg_outputs.append(self.final_nonlin(self.seg_outputs_1[u](x1))) - - if self._deep_supervision and self.do_ds: - return tuple([seg_outputs[-1]] + [i(j) for i, j in - zip(list(self.upscale_logits_ops)[::-1], seg_outputs[:-1][::-1])]) - else: - return seg_outputs[-1] - - @staticmethod - def compute_approx_vram_consumption(patch_size, num_pool_per_axis, base_num_features, max_num_features, - num_modalities, num_classes, pool_op_kernel_sizes, deep_supervision=False, - conv_per_stage=2): - """ - This only applies for num_conv_per_stage and convolutional_upsampling=True - not real vram consumption. just a constant term to which the vram consumption will be approx proportional - (+ offset for parameter storage) - :param deep_supervision: - :param patch_size: - :param num_pool_per_axis: - :param base_num_features: - :param max_num_features: - :param num_modalities: - :param num_classes: - :param pool_op_kernel_sizes: - :return: - """ - if not isinstance(num_pool_per_axis, np.ndarray): - num_pool_per_axis = np.array(num_pool_per_axis) - - npool = len(pool_op_kernel_sizes) - - map_size = np.array(patch_size) - tmp = np.int64((conv_per_stage * 2 + 1) * np.prod(map_size, dtype=np.int64) * base_num_features + - num_modalities * np.prod(map_size, dtype=np.int64) + - num_classes * np.prod(map_size, dtype=np.int64)) - - num_feat = base_num_features - - for p in range(npool): - for pi in range(len(num_pool_per_axis)): - map_size[pi] /= pool_op_kernel_sizes[p][pi] - num_feat = min(num_feat * 2, max_num_features) - # num_blocks = (conv_per_stage * 2 + 1) if p < (npool - 1) else conv_per_stage # conv_per_stage + conv_per_stage for the convs of encode/decode and 1 for transposed conv - num_blocks = (conv_per_stage * 5 + 1) if p < (npool - 1) else conv_per_stage # conv_per_stage + conv_per_stage for the convs of encode/decode*2 and 1 for transposed conv - tmp += num_blocks * np.prod(map_size, dtype=np.int64) * num_feat - if deep_supervision and p < (npool - 2): - tmp += np.prod(map_size, dtype=np.int64) * num_classes - # print(p, map_size, num_feat, tmp) - return tmp diff --git a/spaces/hoang1007/wav2vec2/README.md b/spaces/hoang1007/wav2vec2/README.md deleted file mode 100644 index 4a7140eb3fd72ff06dfe82f646a08d6908a7dc5b..0000000000000000000000000000000000000000 --- a/spaces/hoang1007/wav2vec2/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Wav2vec2 -emoji: 🔥 -colorFrom: purple -colorTo: gray -sdk: gradio -sdk_version: 3.13.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/huggan/sim2real/app.py b/spaces/huggan/sim2real/app.py deleted file mode 100644 index 5bcc37afb686799d5fcd193d4d65d9a9da7269b9..0000000000000000000000000000000000000000 --- a/spaces/huggan/sim2real/app.py +++ /dev/null @@ -1,71 +0,0 @@ - -import os - -from PIL import Image -from torchvision import transforms as T -from torchvision.transforms import Compose, Resize, ToTensor, Normalize, RandomCrop, RandomHorizontalFlip -from torchvision.utils import make_grid -from torch.utils.data import DataLoader -from huggan.pytorch.cyclegan.modeling_cyclegan import GeneratorResNet -import torch.nn as nn -import torch -import gradio as gr - -from collections import OrderedDict -import glob - - - - -def pred_pipeline(img, transforms): - orig_shape = img.shape - input = transforms(img) - input = input.unsqueeze(0) - output_real = sim2real(input) - output_syn = real2sim(output_real) - out_img_real = make_grid(output_real, - nrow=1, normalize=True) - out_syn_real = make_grid(output_syn, - nrow=1, normalize=True) - - - - out_transform = Compose([ - T.Resize(orig_shape[:2]), - T.ToPILImage() - ]) - return out_transform(out_img_real), out_transform(out_syn_real) - - - - -n_channels = 3 -image_size = 512 -input_shape = (image_size, image_size) - -transform = Compose([ - T.ToPILImage(), - T.Resize(input_shape), - ToTensor(), - Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), - ]) - - -sim2real = GeneratorResNet.from_pretrained('Chris1/sim2real-512', input_shape=(n_channels, image_size, image_size), - num_residual_blocks=9) -real2sim = GeneratorResNet.from_pretrained('Chris1/real2sim-512', input_shape=(n_channels, image_size, image_size), - num_residual_blocks=9) - -gr.Interface(lambda image: pred_pipeline(image, transform), - inputs=gr.inputs.Image( label='input synthetic image'), - outputs=[ - gr.outputs.Image( type="pil",label='GAN sim2real prediction: style transfer of the input to the real world '), - gr.outputs.Image( type="pil",label='GAN real2sim prediction: translation to synthetic of the above prediction') - ],#plot, - title = "GTA5(simulated) to Cityscapes (real) translation", - examples = [ - [example] for example in glob.glob('./samples/*.png') - ])\ - .launch() - - diff --git a/spaces/huggingface-projects/diffuse-the-rest/build/_app/immutable/components/pages/_layout.svelte-f7e87a93.js b/spaces/huggingface-projects/diffuse-the-rest/build/_app/immutable/components/pages/_layout.svelte-f7e87a93.js deleted file mode 100644 index 79d515949f13dfdbdf746fad01336bc244eebbe2..0000000000000000000000000000000000000000 --- a/spaces/huggingface-projects/diffuse-the-rest/build/_app/immutable/components/pages/_layout.svelte-f7e87a93.js +++ /dev/null @@ -1 +0,0 @@ -import{S as l,i,s as r,B as u,C as f,D as _,E as c,f as p,t as d}from"../../chunks/index-032ac624.js";function m(n){let s;const o=n[1].default,e=u(o,n,n[0],null);return{c(){e&&e.c()},l(t){e&&e.l(t)},m(t,a){e&&e.m(t,a),s=!0},p(t,[a]){e&&e.p&&(!s||a&1)&&f(e,o,t,t[0],s?c(o,t[0],a,null):_(t[0]),null)},i(t){s||(p(e,t),s=!0)},o(t){d(e,t),s=!1},d(t){e&&e.d(t)}}}function $(n,s,o){let{$$slots:e={},$$scope:t}=s;return n.$$set=a=>{"$$scope"in a&&o(0,t=a.$$scope)},[t,e]}class h extends l{constructor(s){super(),i(this,s,$,m,r,{})}}export{h as default}; diff --git a/spaces/hylee/apdrawing/APDrawingGAN2/train.py b/spaces/hylee/apdrawing/APDrawingGAN2/train.py deleted file mode 100644 index ba45ffdf48b0e1a189caf8d89a455bcdb3bec780..0000000000000000000000000000000000000000 --- a/spaces/hylee/apdrawing/APDrawingGAN2/train.py +++ /dev/null @@ -1,67 +0,0 @@ -import time -from options.train_options import TrainOptions -from data import CreateDataLoader -from models import create_model -from util.visualizer import Visualizer - -if __name__ == '__main__': - start = time.time() - opt = TrainOptions().parse() - data_loader = CreateDataLoader(opt) - dataset = data_loader.load_data() - dataset_size = len(data_loader) - print('#training images = %d' % dataset_size) - - model = create_model(opt) - model.setup(opt) - visualizer = Visualizer(opt) - total_steps = 0 - model.save_networks2(opt.which_epoch) - - for epoch in range(opt.epoch_count, opt.niter + opt.niter_decay + 1): - epoch_start_time = time.time() - iter_data_time = time.time() - epoch_iter = 0 - - for i, data in enumerate(dataset): - iter_start_time = time.time() - if total_steps % opt.print_freq == 0: - t_data = iter_start_time - iter_data_time - visualizer.reset() - total_steps += opt.batch_size - epoch_iter += opt.batch_size - model.set_input(data) - model.optimize_parameters() - - if total_steps % opt.display_freq == 0: - save_result = total_steps % opt.update_html_freq == 0 - visualizer.display_current_results(model.get_current_visuals(), epoch, save_result) - #print('display',total_steps) - - if total_steps % opt.print_freq == 0:#print freq 100 - losses = model.get_current_losses() - t = (time.time() - iter_start_time) / opt.batch_size - visualizer.print_current_losses(epoch, epoch_iter, losses, t, t_data) - if opt.display_id > 0: - visualizer.plot_current_losses(epoch, float(epoch_iter) / dataset_size, opt, losses) - - if total_steps % opt.save_latest_freq == 0: - print('saving the latest model (epoch %d, total_steps %d)' % - (epoch, total_steps)) - #model.save_networks('latest') - model.save_networks2('latest') - - iter_data_time = time.time() - if epoch % opt.save_epoch_freq == 0: - print('saving the model at the end of epoch %d, iters %d' % - (epoch, total_steps)) - #model.save_networks('latest') - #model.save_networks(epoch) - model.save_networks2('latest') - model.save_networks2(epoch) - - print('End of epoch %d / %d \t Time Taken: %d sec' % - (epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time)) - model.update_learning_rate() - - print('Total Time Taken: %d sec' % (time.time() - start)) diff --git a/spaces/hysts/ControlNet-v1-1/app_scribble_interactive.py b/spaces/hysts/ControlNet-v1-1/app_scribble_interactive.py deleted file mode 100644 index 12574077a5e8d890fbf0b0f9558348a737153123..0000000000000000000000000000000000000000 --- a/spaces/hysts/ControlNet-v1-1/app_scribble_interactive.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python - -import gradio as gr -import numpy as np - -from settings import ( - DEFAULT_IMAGE_RESOLUTION, - DEFAULT_NUM_IMAGES, - MAX_IMAGE_RESOLUTION, - MAX_NUM_IMAGES, - MAX_SEED, -) -from utils import randomize_seed_fn - - -def create_canvas(w, h): - return np.zeros(shape=(h, w, 3), dtype=np.uint8) + 255 - - -def create_demo(process): - with gr.Blocks() as demo: - with gr.Row(): - with gr.Column(): - canvas_width = gr.Slider( - label="Canvas width", - minimum=256, - maximum=MAX_IMAGE_RESOLUTION, - value=DEFAULT_IMAGE_RESOLUTION, - step=1, - ) - canvas_height = gr.Slider( - label="Canvas height", - minimum=256, - maximum=MAX_IMAGE_RESOLUTION, - value=DEFAULT_IMAGE_RESOLUTION, - step=1, - ) - create_button = gr.Button("Open drawing canvas!") - image = gr.Image(tool="sketch", brush_radius=10) - prompt = gr.Textbox(label="Prompt") - run_button = gr.Button("Run") - with gr.Accordion("Advanced options", open=False): - num_samples = gr.Slider( - label="Number of images", minimum=1, maximum=MAX_NUM_IMAGES, value=DEFAULT_NUM_IMAGES, step=1 - ) - image_resolution = gr.Slider( - label="Image resolution", - minimum=256, - maximum=MAX_IMAGE_RESOLUTION, - value=DEFAULT_IMAGE_RESOLUTION, - step=256, - ) - num_steps = gr.Slider(label="Number of steps", minimum=1, maximum=100, value=20, step=1) - guidance_scale = gr.Slider(label="Guidance scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1) - seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0) - randomize_seed = gr.Checkbox(label="Randomize seed", value=True) - a_prompt = gr.Textbox(label="Additional prompt", value="best quality, extremely detailed") - n_prompt = gr.Textbox( - label="Negative prompt", - value="longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality", - ) - with gr.Column(): - result = gr.Gallery(label="Output", show_label=False, columns=2, object_fit="scale-down") - - create_button.click( - fn=create_canvas, - inputs=[canvas_width, canvas_height], - outputs=image, - queue=False, - api_name=False, - ) - - inputs = [ - image, - prompt, - a_prompt, - n_prompt, - num_samples, - image_resolution, - num_steps, - guidance_scale, - seed, - ] - prompt.submit( - fn=randomize_seed_fn, - inputs=[seed, randomize_seed], - outputs=seed, - queue=False, - api_name=False, - ).then( - fn=process, - inputs=inputs, - outputs=result, - api_name=False, - ) - run_button.click( - fn=randomize_seed_fn, - inputs=[seed, randomize_seed], - outputs=seed, - queue=False, - api_name=False, - ).then( - fn=process, - inputs=inputs, - outputs=result, - ) - return demo - - -if __name__ == "__main__": - from model import Model - - model = Model(task_name="scribble") - demo = create_demo(model.process_scribble_interactive) - demo.queue().launch() diff --git a/spaces/hysts/ControlNet-with-Anything-v4/README.md b/spaces/hysts/ControlNet-with-Anything-v4/README.md deleted file mode 100644 index 0444e9ddab336d3ac7bca1a85b665411cb69f321..0000000000000000000000000000000000000000 --- a/spaces/hysts/ControlNet-with-Anything-v4/README.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: ControlNet + Anything v4.0 -emoji: 😻 -colorFrom: pink -colorTo: blue -sdk: gradio -sdk_version: 3.36.1 -python_version: 3.10.11 -app_file: app.py -pinned: false -license: mit -suggested_hardware: t4-medium -duplicated_from: hysts/ControlNet ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Deep Freeze 8.60.220.5582 Crack Plus Activation Code Free Download 2019 !FULL!.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Deep Freeze 8.60.220.5582 Crack Plus Activation Code Free Download 2019 !FULL!.md deleted file mode 100644 index b9c97cfa3e88914f3648e082df03082ceb58c57b..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Deep Freeze 8.60.220.5582 Crack Plus Activation Code Free Download 2019 !FULL!.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Deep Freeze 8.60.220.5582 Crack Plus Activation Code Free Download 2019


    DOWNLOADhttps://urlin.us/2uEyvr



    -
    - 3cee63e6c2
    -
    -
    -

    diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Film Semi Blue Thailand EXCLUSIVE.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Film Semi Blue Thailand EXCLUSIVE.md deleted file mode 100644 index ba3d4852b568790b18e865d4c8aea8f7978cd504..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Film Semi Blue Thailand EXCLUSIVE.md +++ /dev/null @@ -1,15 +0,0 @@ -

    film semi blue thailand


    Downloadhttps://urlin.us/2uEwF8



    -
    -4746 film semi thailand FREE videos found on XVIDEOS for this search. Free videos. -Watch video Semi-thailand.com on Redtube, home of free Big Tits porn videos and Brunette sex movies online. -Video length: (50:29) - Uploaded by Semi-thailand.com - Starring Pornstar: Evelin Rain. -Free videos. -Watch porn videos for free. -Video by category. -Porn videos and sex videos online. -Look... -The best porn videos for free and without registration on the site pornoxyu.biz, you won't regret it! -Every day fresh fucking in good quality only on site pornfuck! 8a78ff9644
    -
    -
    -

    diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/KMSpico 9.2.3 Final-ThumperDC BEST Download Pc.md b/spaces/inplisQlawa/anything-midjourney-v4-1/KMSpico 9.2.3 Final-ThumperDC BEST Download Pc.md deleted file mode 100644 index 304f3f7d9ad9891c31112995334395b34d4660f4..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/KMSpico 9.2.3 Final-ThumperDC BEST Download Pc.md +++ /dev/null @@ -1,122 +0,0 @@ - -

    KMSpico 9.2.3 Final-ThumperDC Download PC - How to Activate Windows and Office for Free

    - -

    If you are looking for a way to activate Windows and Office for free, you might have heard of KMSpico 9.2.3 Final-ThumperDC, a tool that can permanently activate any version of Windows or Microsoft Office within seconds. But what is KMSpico 9.2.3 Final-ThumperDC and how does it work? And more importantly, how can you download KMSpico 9.2.3 Final-ThumperDC for PC and use it safely and legally? In this article, we will answer these questions and show you how to download KMSpico 9.2.3 Final-ThumperDC for PC and activate Windows and Office for free.

    - -

    What is KMSpico 9.2.3 Final-ThumperDC

    - -

    KMSpico 9.2.3 Final-ThumperDC is a tool that can activate Windows and Office by emulating a Key Management Service (KMS) server on your PC. KMS is a technology that Microsoft uses to activate products on a large scale, such as in enterprises or schools. KMS requires a local server that periodically renews the activation of the products connected to it.

    -

    KMSpico 9.2.3 Final-ThumperDC download pc


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



    - -

    KMSpico 9.2.3 Final-ThumperDC mimics this process by creating a virtual KMS server on your PC and registering your Windows and Office products as if they were connected to a real KMS server. This way, you can activate Windows and Office without using a product key or paying for a license.

    - -

    KMSpico 9.2.3 Final-ThumperDC is the latest version of KMSpico, a tool that has been around for years and has been updated frequently to support the latest versions of Windows and Office. KMSpico 9.2.3 Final-ThumperDC can activate:

    - -
      -
    • Windows Vista Business/N/Enterprise/N
    • -
    • Windows 7 Professional/N/Enterprise/N
    • -
    • Windows 8 All
    • -
    • Windows 8.1 All
    • -
    • Windows 10 All
    • -
    • Office 2010/2013/2016/2019 All
    • -
    • Windows Server 2008/Standard/Datacenter/Enterprise/2008R2/Standard/Datacenter/Enterprise
    • -
    • Windows Server 2012/Standard/Datacenter/2012R2/Standard/Datacenter
    • -
    • Windows Server 2016/Standard/Datacenter
    • -
    • Windows Server 2019/Standard/Datacenter
    • -
    - -

    How to Download KMSpico 9.2.3 Final-ThumperDC for PC

    - -

    If you want to download KMSpico 9.2.3 Final-ThumperDC for PC, you need to be careful about where you get it from, as there are many fake or malicious websites that claim to offer KMSpico 9.2.3 Final-ThumperDC but actually deliver viruses or malware to your PC.

    - -

    To download KMSpico 9.2.3 Final-ThumperDC for PC safely and legally, you need to find a reliable and trusted source that offers the original and clean version of KMSpico 9.2.3 Final-ThumperDC without any modifications or additions.

    - -

    One of the best sources to download KMSpico 9.2.3 Final-ThumperDC for PC is the Internet Archive, a non-profit digital library that preserves millions of free books, movies, software, music and more on its website.

    - -

    To download KMSpico 9.2.3 Final-ThumperDC for PC from the Internet Archive, follow these steps:

    -

    - -
      -
    1. Go to https://archive.org/details/KMSpico.9.2.3
    2. -
    3. Click on the "Download Options" button on the right side of the page.
    4. -
    5. Select the "ZIP" option under "Compressed Files". This will download a ZIP file containing KMSpico 9.2.3 Final-ThumperDC.
    6. -
    7. Extract the ZIP file to a folder on your PC using a tool like WinRAR or 7-Zip.
    8. -
    9. Open the folder and run the "KMSpico_setup.exe" file as administrator.
    10. -
    11. Follow the instructions on the screen to install KMSpico 9.2.3 Final-ThumperDC on your PC.
    12. -
    - -

    How to Use KMSpico 9.2.3 Final-ThumperDC to Activate Windows and Office for Free

    - -

    After installing KMSpico 9.2.3 Final-ThumperDC on your PC, you can use it to activate Windows and Office for free by following these steps:

    - -
      -
    1. Make sure you have an internet connection.
    2. -
    3. Disable any antivirus or firewall software on your PC temporarily, as they might interfere with KMSpico 9.2.3 Final-ThumperDC.
    4. -
    5. Go to the folder where you installed KMSpico 9.2.3 Final-ThumperDC and run the "KMSELDI.exe" file as administrator.
    6. -
    7. A window will pop up with some buttons and information.
    8. -
    9. Click on the red button with an "i" icon on it to check the status of your Windows and Office products.
    10. -
    11. If they are not activated, click on the red button with a "K" icon on it to activate them.
    12. -
    13. A message will appear saying "Successfully Activated". Click on "OK".
    14. -
    15. You can also click on the blue button with a "T" icon on it to create a backup of your activation in case you need to restore it later.
    16. -
    17. You can also click on the green button with an "S" icon on it to check for updates of KMSpico 9.2.3 Final-ThumperDC.
    18. -
    19. You can also click on the yellow button with an "A" icon on it to set KMSpico 9.2.3 Final-ThumperDC to run automatically at startup.
    20. -
    21. You can also click on the purple button with an "L" icon on it to see the log of KMSpico 9.2.3 Final-ThumperDC's activity.
    22. -
    23. You can also click on the orange button with an "X" icon on it to exit KMSpico 9.2.3 Final-ThumperDC.
    24. -
    - -

    Congratulations! You have successfully activated Windows and Office for free using KMSpico 9.2

    -

    What are the Benefits of Using KMSpico 9.2.3 Final-ThumperDC to Activate Windows and Office for Free

    - -

    Using KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free has many benefits that can make your PC experience better and easier. Here are some of them:

    - -
      -
    • You can use all the features and functions of Windows and Office without any limitations or restrictions. You can customize your PC settings, access updates and security patches, use online services and cloud storage, create and edit documents and presentations, and more.
    • -
    • You can save money and time by not having to buy a product key or a license for Windows and Office. You don't have to spend hundreds of dollars or rupees to get a genuine product key or a license for Windows and Office. You also don't have to waste time searching for a valid product key or a license online or offline.
    • -
    • You can avoid the annoying and embarrassing messages and notifications that tell you that your Windows or Office is not activated or genuine. You don't have to deal with the black screen of windows genuine problem, the watermark on your desktop, the pop-ups that ask you to activate your Windows or Office, or the reduced functionality mode that limits your access to Windows or Office features.
    • -
    • You can activate Windows and Office for free in a simple and fast way. You don't have to follow complicated steps or use multiple tools to activate Windows and Office for free. You just have to download KMSpico 9.2.3 Final-ThumperDC for PC, install it, run it, and click a few buttons to activate Windows and Office for free in seconds.
    • -
    - -

    What are the Risks of Using KMSpico 9.2.3 Final-ThumperDC to Activate Windows and Office for Free

    - -

    While using KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free has many benefits, it also has some risks that you should be aware of before using it. Here are some of them:

    - -
      -
    • You might violate the terms and conditions of Microsoft by using KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free. Microsoft does not support or endorse the use of KMSpico 9.2.3 Final-ThumperDC or any other tool that can activate Windows and Office without a product key or a license. Microsoft considers this as piracy and illegal activity that can harm its business and reputation.
    • -
    • You might expose your PC to viruses or malware by downloading KMSpico 9.2.3 Final-ThumperDC from untrusted sources. As we mentioned earlier, there are many fake or malicious websites that claim to offer KMSpico 9.2.3 Final-ThumperDC but actually deliver viruses or malware to your PC. These viruses or malware can damage your PC, steal your personal information, or compromise your online security.
    • -
    • You might face some technical issues or errors by using KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free. KMSpico 9.2.3 Final-ThumperDC might not work properly with some versions of Windows or Office, especially if they are updated frequently by Microsoft. KMSpico 9.2.3 Final-ThumperDC might also interfere with some antivirus or firewall software on your PC, causing them to malfunction or block KMSpico 9.2.3 Final-ThumperDC.
    • -
    - -

    How to Use KMSpico 9.2.3 Final-ThumperDC Safely and Legally

    - -

    If you want to use KMSpico 9.2 -

    How to Use KMSpico 9.2.3 Final-ThumperDC Safely and Legally

    - -

    If you want to use KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free, but you also want to avoid the risks and respect the terms and conditions of Microsoft, you might want to follow some tips and precautions that can help you use KMSpico 9.2.3 Final-ThumperDC safely and legally. Here are some of them:

    - -
      -
    • Use KMSpico 9.2.3 Final-ThumperDC only if you own a legal Windows or Office product key or license. This way, you can prove that you have purchased a genuine copy of Windows or Office and that you are not pirating or stealing them. You can also use KMSpico 9.2.3 Final-ThumperDC as a backup or alternative method to activate Windows or Office in case your product key or license fails or gets lost.
    • -
    • Download KMSpico 9.2.3 Final-ThumperDC only from trusted and reliable sources. This way, you can avoid downloading viruses or malware that can harm your PC or compromise your online security. You can also verify the authenticity and integrity of KMSpico 9.2.3 Final-ThumperDC by checking its digital signature or hash value.
    • -
    • Disable any antivirus or firewall software on your PC temporarily before using KMSpico 9.2.3 Final-ThumperDC. This way, you can prevent any interference or conflict between KMSpico 9.2.3 Final-ThumperDC and your antivirus or firewall software that might cause them to malfunction or block KMSpico 9.2.3 Final-ThumperDC. You can also add KMSpico 9.2.3 Final-ThumperDC to the exception list of your antivirus or firewall software to allow it to run smoothly.
    • -
    • Use KMSpico 9.2.3 Final-ThumperDC only for personal and non-commercial purposes. This way, you can avoid violating the intellectual property rights of Microsoft and respect its business and reputation. You can also avoid any legal consequences or penalties that might arise from using KMSpico 9.2.3 Final-ThumperDC for commercial purposes.
    • -
    - -

    Conclusion

    - -

    KMSpico 9.2.3 Final-ThumperDC is a tool that can activate Windows and Office for free by emulating a KMS server on your PC. It can activate any version of Windows or Office without using a product key or paying for a license.

    - -

    In this article, we have shown you how to download KMSpico 9.2.3 Final-ThumperDC for PC safely and legally from the Internet Archive, and how to use it to activate Windows and Office for free in a simple and fast way.

    - -

    We have also explained the benefits and risks of using KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free, and how to use it safely and legally by following some tips and precautions.

    - -

    We hope this article has been helpful for you. If you have any questions or suggestions, please feel free to leave a comment below. Thank you for reading!

    -

    Conclusion

    - -

    KMSpico 9.2.3 Final-ThumperDC is a tool that can activate Windows and Office for free by emulating a KMS server on your PC. It can activate any version of Windows or Office without using a product key or paying for a license.

    - -

    In this article, we have shown you how to download KMSpico 9.2.3 Final-ThumperDC for PC safely and legally from the Internet Archive, and how to use it to activate Windows and Office for free in a simple and fast way.

    - -

    We have also explained the benefits and risks of using KMSpico 9.2.3 Final-ThumperDC to activate Windows and Office for free, and how to use it safely and legally by following some tips and precautions.

    - -

    We hope this article has been helpful for you. If you have any questions or suggestions, please feel free to leave a comment below. Thank you for reading!

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Lord Of The Rings Battle For Middle Earth Crack No Cd.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Lord Of The Rings Battle For Middle Earth Crack No Cd.md deleted file mode 100644 index 312f32d7e6c46989e5d5d5e606000f870942f0a8..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Lord Of The Rings Battle For Middle Earth Crack No Cd.md +++ /dev/null @@ -1,14 +0,0 @@ -

    lord of the rings battle for middle earth crack no cd


    Download File > https://urlin.us/2uExEE



    - -Free downloads similar to Lord Of The Rings: Battle For Middle Earth V1.0. Dat no cd for Lord of the Rings: Battle for Middle Earth, Lord ... Crack, NoCD/Non-Cd, NoDVD, trainers, save files, save, walkthrough, patches ... -Download ... -D:\\Games\\Lord of The Rings: The Battle for Middle-earth\\Ring of Arguna\\v1.0c.exe -d2c.exe -r2c.exe ... -Download torrent [200] Lord of the Rings: The Battle for Middle-earth (2006) PC-RePack from category Action ... -How about a crack? -Lord of the Rings the Battle for Middle-earth v1.12 (2007) PC ... -Is there a crack? -D:Games\\Lord of The Rings... -Download torrent [200] Lord of the Rings: The Battle for Middle- 8a78ff9644
    -
    -
    -

    diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Ls-land-issue-06-little-pirates-lsp-008-by-zic.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Ls-land-issue-06-little-pirates-lsp-008-by-zic.md deleted file mode 100644 index 0d29ce409abad9a3410cc3746266ad5f9a3c8171..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Ls-land-issue-06-little-pirates-lsp-008-by-zic.md +++ /dev/null @@ -1,20 +0,0 @@ -

    ls-land-issue-06-little-pirates-lsp-008-by-zic


    Download Filehttps://urlin.us/2uEvh6



    - -April 19, 2017 - Do you have any recommendations to fix this problem? ... the version available in our store in a few days. ... 7383628160 Feb 2021 — laurquen f4bc01c98b antogent Feb 2, 2022 8:24 am.... I have some c++ code that creates a thread and -18 Apr. 2018 Q: How can I know when a stream will be created? -Answer: ... -How to find out when a new thread is created? -And how can you find out when it ends? -(Thread. ... -Thread.Queue.UsingSynchronizedBlockingQueue = true; thread. ... -thread. -invoke(); Thread.Sleep(1000); thread.Queue. -Clear(); ... -sleep(10000); -Dec 25 2019 · How to stop a thread in Windows 7, 8, 10? ... -Queue. -Clear(); thread. ... -Thread. 8a78ff9644
    -
    -
    -

    diff --git a/spaces/inreVtussa/clothingai/Examples/Autodata Na Srpskom Crack LINK.md b/spaces/inreVtussa/clothingai/Examples/Autodata Na Srpskom Crack LINK.md deleted file mode 100644 index 5c3afdc82f77d23ce306cd1c5db1f6ebbf0c17e5..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Autodata Na Srpskom Crack LINK.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Autodata Na Srpskom Crack


    Download Zip ===> https://tiurll.com/2uCleP



    -
    -Delphi 2016 with keygen install videohttps://cartruckdiagnostictools.co.uk. 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/jackli888/stable-diffusion-webui/modules/safe.py b/spaces/jackli888/stable-diffusion-webui/modules/safe.py deleted file mode 100644 index b51ee885014e4070537f16d35da381402db0db6c..0000000000000000000000000000000000000000 --- a/spaces/jackli888/stable-diffusion-webui/modules/safe.py +++ /dev/null @@ -1,192 +0,0 @@ -# this code is adapted from the script contributed by anon from /h/ - -import io -import pickle -import collections -import sys -import traceback - -import torch -import numpy -import _codecs -import zipfile -import re - - -# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage -TypedStorage = torch.storage.TypedStorage if hasattr(torch.storage, 'TypedStorage') else torch.storage._TypedStorage - - -def encode(*args): - out = _codecs.encode(*args) - return out - - -class RestrictedUnpickler(pickle.Unpickler): - extra_handler = None - - def persistent_load(self, saved_id): - assert saved_id[0] == 'storage' - return TypedStorage() - - def find_class(self, module, name): - if self.extra_handler is not None: - res = self.extra_handler(module, name) - if res is not None: - return res - - if module == 'collections' and name == 'OrderedDict': - return getattr(collections, name) - if module == 'torch._utils' and name in ['_rebuild_tensor_v2', '_rebuild_parameter', '_rebuild_device_tensor_from_numpy']: - return getattr(torch._utils, name) - if module == 'torch' and name in ['FloatStorage', 'HalfStorage', 'IntStorage', 'LongStorage', 'DoubleStorage', 'ByteStorage', 'float32']: - return getattr(torch, name) - if module == 'torch.nn.modules.container' and name in ['ParameterDict']: - return getattr(torch.nn.modules.container, name) - if module == 'numpy.core.multiarray' and name in ['scalar', '_reconstruct']: - return getattr(numpy.core.multiarray, name) - if module == 'numpy' and name in ['dtype', 'ndarray']: - return getattr(numpy, name) - if module == '_codecs' and name == 'encode': - return encode - if module == "pytorch_lightning.callbacks" and name == 'model_checkpoint': - import pytorch_lightning.callbacks - return pytorch_lightning.callbacks.model_checkpoint - if module == "pytorch_lightning.callbacks.model_checkpoint" and name == 'ModelCheckpoint': - import pytorch_lightning.callbacks.model_checkpoint - return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint - if module == "__builtin__" and name == 'set': - return set - - # Forbid everything else. - raise Exception(f"global '{module}/{name}' is forbidden") - - -# Regular expression that accepts 'dirname/version', 'dirname/data.pkl', and 'dirname/data/' -allowed_zip_names_re = re.compile(r"^([^/]+)/((data/\d+)|version|(data\.pkl))$") -data_pkl_re = re.compile(r"^([^/]+)/data\.pkl$") - -def check_zip_filenames(filename, names): - for name in names: - if allowed_zip_names_re.match(name): - continue - - raise Exception(f"bad file inside {filename}: {name}") - - -def check_pt(filename, extra_handler): - try: - - # new pytorch format is a zip file - with zipfile.ZipFile(filename) as z: - check_zip_filenames(filename, z.namelist()) - - # find filename of data.pkl in zip file: '/data.pkl' - data_pkl_filenames = [f for f in z.namelist() if data_pkl_re.match(f)] - if len(data_pkl_filenames) == 0: - raise Exception(f"data.pkl not found in {filename}") - if len(data_pkl_filenames) > 1: - raise Exception(f"Multiple data.pkl found in {filename}") - with z.open(data_pkl_filenames[0]) as file: - unpickler = RestrictedUnpickler(file) - unpickler.extra_handler = extra_handler - unpickler.load() - - except zipfile.BadZipfile: - - # if it's not a zip file, it's an olf pytorch format, with five objects written to pickle - with open(filename, "rb") as file: - unpickler = RestrictedUnpickler(file) - unpickler.extra_handler = extra_handler - for i in range(5): - unpickler.load() - - -def load(filename, *args, **kwargs): - return load_with_extra(filename, extra_handler=global_extra_handler, *args, **kwargs) - - -def load_with_extra(filename, extra_handler=None, *args, **kwargs): - """ - this function is intended to be used by extensions that want to load models with - some extra classes in them that the usual unpickler would find suspicious. - - Use the extra_handler argument to specify a function that takes module and field name as text, - and returns that field's value: - - ```python - def extra(module, name): - if module == 'collections' and name == 'OrderedDict': - return collections.OrderedDict - - return None - - safe.load_with_extra('model.pt', extra_handler=extra) - ``` - - The alternative to this is just to use safe.unsafe_torch_load('model.pt'), which as the name implies is - definitely unsafe. - """ - - from modules import shared - - try: - if not shared.cmd_opts.disable_safe_unpickle: - check_pt(filename, extra_handler) - - except pickle.UnpicklingError: - print(f"Error verifying pickled file from {filename}:", file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - print("-----> !!!! The file is most likely corrupted !!!! <-----", file=sys.stderr) - print("You can skip this check with --disable-safe-unpickle commandline argument, but that is not going to help you.\n\n", file=sys.stderr) - return None - - except Exception: - print(f"Error verifying pickled file from {filename}:", file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - print("\nThe file may be malicious, so the program is not going to read it.", file=sys.stderr) - print("You can skip this check with --disable-safe-unpickle commandline argument.\n\n", file=sys.stderr) - return None - - return unsafe_torch_load(filename, *args, **kwargs) - - -class Extra: - """ - A class for temporarily setting the global handler for when you can't explicitly call load_with_extra - (because it's not your code making the torch.load call). The intended use is like this: - -``` -import torch -from modules import safe - -def handler(module, name): - if module == 'torch' and name in ['float64', 'float16']: - return getattr(torch, name) - - return None - -with safe.Extra(handler): - x = torch.load('model.pt') -``` - """ - - def __init__(self, handler): - self.handler = handler - - def __enter__(self): - global global_extra_handler - - assert global_extra_handler is None, 'already inside an Extra() block' - global_extra_handler = self.handler - - def __exit__(self, exc_type, exc_val, exc_tb): - global global_extra_handler - - global_extra_handler = None - - -unsafe_torch_load = torch.load -torch.load = load -global_extra_handler = None - diff --git a/spaces/jamesyoung999/whisper_word_timestamps/README.md b/spaces/jamesyoung999/whisper_word_timestamps/README.md deleted file mode 100644 index cdbb285c670bdb31f79299180bc5ebbae20b6a40..0000000000000000000000000000000000000000 --- a/spaces/jamesyoung999/whisper_word_timestamps/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Whisper Word-Level Timestamps -emoji: 💭⏰ -colorFrom: yellow -colorTo: indigo -sdk: gradio -sdk_version: 3.35.2 -app_file: app.py -pinned: false -license: apache-2.0 -duplicated_from: Matthijs/whisper_word_timestamps ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/jbilcke-hf/VideoChain-UI/src/app/studio/[ownerId]/page.tsx b/spaces/jbilcke-hf/VideoChain-UI/src/app/studio/[ownerId]/page.tsx deleted file mode 100644 index 262a222374fc00cba537297654839b0059c63d5a..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/VideoChain-UI/src/app/studio/[ownerId]/page.tsx +++ /dev/null @@ -1,22 +0,0 @@ -"use server" - -import Head from "next/head" - -import { getVideos } from "@/server" - -import Main from "./main" - -export default async function StudioPage({ params: { ownerId } }: { params: { ownerId: string }}) { - const videos = await getVideos(ownerId) - - return ( -
    - - - -
    -
    -
    -
    - ) -} \ No newline at end of file diff --git a/spaces/jbilcke-hf/VideoChain-UI/src/components/ui/alert.tsx b/spaces/jbilcke-hf/VideoChain-UI/src/components/ui/alert.tsx deleted file mode 100644 index f589783193a6cfe14032a77b89055cb3e920fe8c..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/VideoChain-UI/src/components/ui/alert.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" - -import { cn } from "@/lib/utils" - -const alertVariants = cva( - "relative w-full rounded-lg border border-stone-200 p-4 [&:has(svg)]:pl-11 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-stone-950 dark:border-stone-800 dark:[&>svg]:text-stone-50", - { - variants: { - variant: { - default: "bg-white text-stone-950 dark:bg-stone-950 dark:text-stone-50", - destructive: - "border-red-500/50 text-red-500 dark:border-red-500 [&>svg]:text-red-500 dark:border-red-900/50 dark:text-red-900 dark:dark:border-red-900 dark:[&>svg]:text-red-900", - }, - }, - defaultVariants: { - variant: "default", - }, - } -) - -const Alert = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes & VariantProps ->(({ className, variant, ...props }, ref) => ( -
    -)) -Alert.displayName = "Alert" - -const AlertTitle = React.forwardRef< - HTMLParagraphElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)) -AlertTitle.displayName = "AlertTitle" - -const AlertDescription = React.forwardRef< - HTMLParagraphElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)) -AlertDescription.displayName = "AlertDescription" - -export { Alert, AlertTitle, AlertDescription } diff --git a/spaces/jbilcke-hf/VideoQuest/src/components/ui/label.tsx b/spaces/jbilcke-hf/VideoQuest/src/components/ui/label.tsx deleted file mode 100644 index 534182176bf87f9308355514adc884d2b69750a5..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/VideoQuest/src/components/ui/label.tsx +++ /dev/null @@ -1,26 +0,0 @@ -"use client" - -import * as React from "react" -import * as LabelPrimitive from "@radix-ui/react-label" -import { cva, type VariantProps } from "class-variance-authority" - -import { cn } from "@/lib/utils" - -const labelVariants = cva( - "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" -) - -const Label = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef & - VariantProps ->(({ className, ...props }, ref) => ( - -)) -Label.displayName = LabelPrimitive.Root.displayName - -export { Label } diff --git a/spaces/jbilcke-hf/observer/src/components/ui/select.tsx b/spaces/jbilcke-hf/observer/src/components/ui/select.tsx deleted file mode 100644 index 704239634b359b9e680dab25275e205e72579f82..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/observer/src/components/ui/select.tsx +++ /dev/null @@ -1,121 +0,0 @@ -"use client" - -import * as React from "react" -import * as SelectPrimitive from "@radix-ui/react-select" -import { Check, ChevronDown } from "lucide-react" - -import { cn } from "@/lib/utils" - -const Select = SelectPrimitive.Root - -const SelectGroup = SelectPrimitive.Group - -const SelectValue = SelectPrimitive.Value - -const SelectTrigger = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - - {children} - - - - -)) -SelectTrigger.displayName = SelectPrimitive.Trigger.displayName - -const SelectContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, position = "popper", ...props }, ref) => ( - - - - {children} - - - -)) -SelectContent.displayName = SelectPrimitive.Content.displayName - -const SelectLabel = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -SelectLabel.displayName = SelectPrimitive.Label.displayName - -const SelectItem = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - - - - - - - - {children} - -)) -SelectItem.displayName = SelectPrimitive.Item.displayName - -const SelectSeparator = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -SelectSeparator.displayName = SelectPrimitive.Separator.displayName - -export { - Select, - SelectGroup, - SelectValue, - SelectTrigger, - SelectContent, - SelectLabel, - SelectItem, - SelectSeparator, -} diff --git a/spaces/jbilcke-hf/splatter-api/README.md b/spaces/jbilcke-hf/splatter-api/README.md deleted file mode 100644 index 0387fe1460328770dd9818c717f36232e5083445..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/splatter-api/README.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: Gaussian Splatting API -emoji: 🎨 -colorFrom: green -colorTo: yellow -sdk: docker -pinned: true -app_port: 7860 ---- - -## Presentation - -### What is this project? - -WARNING - This project is not finished! - -Gaussian Splatting API is a REST API to generate 3D Gaussian Splatting scenes from a set of images. - -It is a wrapper around [MrNERF/gaussian-splatting-cuda](https://github.com/MrNeRF/gaussian-splatting-cuda). - -### TODO - -- [x] Compile gaussian-splatting-cuda with Docker -- [ ] Support upload of assets -- [ ] Support download of scenes - -### License - -The server wrapping code is open-source, but the code engine [gaussian-splatting-cuda](https://github.com/MrNeRF/gaussian-splatting-cuda) is based on [project by the Inria and the Max Planck Institut for Informatik (MPII)](https://github.com/graphdeco-inria/gaussian-splatting). - -This is a [publicly funded project](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/) with a [non-commercial license](GAUSSIAN-SPLATTING-LICENCE.md). - -### So I can't use it for commercial apps? - -You will have to talk with the original rightholders at the INRIA and MPII. - -Also, please tell me if you know about any alternative project with a fully permissive open-source licensing. - - -## Running on your machine - -### Prerequisites - -You need a machine with CUDA, a GPU etc - -### Environment variables - -- `STORAGE_PATH`: on HF use `/data`, on a local you can use `.sandbox/` - -### Deployment to Hugging Face - -This can take some time. - -note: this is a long build (~30 min) - diff --git a/spaces/jie1/succ1/DLKcat/DeeplearningApproach/Code/preprocess/sabio_kcat_unisubstrate.py b/spaces/jie1/succ1/DLKcat/DeeplearningApproach/Code/preprocess/sabio_kcat_unisubstrate.py deleted file mode 100644 index b348189b89d40320e2bb13dd1286c748858a2b13..0000000000000000000000000000000000000000 --- a/spaces/jie1/succ1/DLKcat/DeeplearningApproach/Code/preprocess/sabio_kcat_unisubstrate.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# coding: utf-8 - -# Author: LE YUAN -# Date: 2020-07-13 - - -import os -import csv - - -# with open("./Kcat_sabio_4_new/%s" %('1.1.1.184.txt'), 'r', encoding="utf-8") as file : -# lines = file.readlines() - -# for line in lines[1:] : -# data = line.strip().split('\t') -# print(data) - - -outfile = open("../../Data/database/Kcat_sabio_4_unisubstrate.tsv", "wt") -# with open("./Kcat_sabio.tsv", "wt") as outfile : -tsv_writer = csv.writer(outfile, delimiter="\t") -tsv_writer.writerow(["EntryID", "Type", "ECNumber", "Substrate", "EnzymeType", "PubMedID", - "Organism", "UniprotID", "Value", "Unit"]) - -filenames = os.listdir('../../Data/database/Kcat_sabio_4') -# print(len(filenames)) # 1741 EC files -i = 0 -j=0 -for filename in filenames : - print(filename[1:-4]) -# # if filename == '1.1.1.184.txt' : - - if filename != '.DS_Store' : - with open("../../Data/database/Kcat_sabio_4/%s" % filename, 'r', encoding="utf-8") as file : - lines = file.readlines() - - for line in lines[1:] : - data = line.strip().split('\t') - # print(data) - try : - if data[7] == 'kcat' and data[9] : - i += 1 - print(i) - print(data) - entryID = data[0] - for line in lines[1:] : - data2 = line.strip().split('\t') - if data2[0] == entryID and data2[7] == 'Km' : - j += 1 - print(j) - tsv_writer.writerow([j, data[7], data[6], data2[8], data[2], data[3], data[4], data[5], data[9], data[-1]]) - except : - continue - -outfile.close() - diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/aiohttp/resolver.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/aiohttp/resolver.py deleted file mode 100644 index 531ce93fccc2d3be442556de644cdc78d31d9c6e..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/aiohttp/resolver.py +++ /dev/null @@ -1,160 +0,0 @@ -import asyncio -import socket -from typing import Any, Dict, List, Optional, Type, Union - -from .abc import AbstractResolver -from .helpers import get_running_loop - -__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") - -try: - import aiodns - - # aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname') -except ImportError: # pragma: no cover - aiodns = None - -aiodns_default = False - - -class ThreadedResolver(AbstractResolver): - """Threaded resolver. - - Uses an Executor for synchronous getaddrinfo() calls. - concurrent.futures.ThreadPoolExecutor is used by default. - """ - - def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: - self._loop = get_running_loop(loop) - - async def resolve( - self, hostname: str, port: int = 0, family: int = socket.AF_INET - ) -> List[Dict[str, Any]]: - infos = await self._loop.getaddrinfo( - hostname, - port, - type=socket.SOCK_STREAM, - family=family, - flags=socket.AI_ADDRCONFIG, - ) - - hosts = [] - for family, _, proto, _, address in infos: - if family == socket.AF_INET6: - if len(address) < 3: - # IPv6 is not supported by Python build, - # or IPv6 is not enabled in the host - continue - if address[3]: # type: ignore[misc] - # This is essential for link-local IPv6 addresses. - # LL IPv6 is a VERY rare case. Strictly speaking, we should use - # getnameinfo() unconditionally, but performance makes sense. - host, _port = socket.getnameinfo( - address, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV - ) - port = int(_port) - else: - host, port = address[:2] - else: # IPv4 - assert family == socket.AF_INET - host, port = address # type: ignore[misc] - hosts.append( - { - "hostname": hostname, - "host": host, - "port": port, - "family": family, - "proto": proto, - "flags": socket.AI_NUMERICHOST | socket.AI_NUMERICSERV, - } - ) - - return hosts - - async def close(self) -> None: - pass - - -class AsyncResolver(AbstractResolver): - """Use the `aiodns` package to make asynchronous DNS lookups""" - - def __init__( - self, - loop: Optional[asyncio.AbstractEventLoop] = None, - *args: Any, - **kwargs: Any - ) -> None: - if aiodns is None: - raise RuntimeError("Resolver requires aiodns library") - - self._loop = get_running_loop(loop) - self._resolver = aiodns.DNSResolver(*args, loop=loop, **kwargs) - - if not hasattr(self._resolver, "gethostbyname"): - # aiodns 1.1 is not available, fallback to DNSResolver.query - self.resolve = self._resolve_with_query # type: ignore - - async def resolve( - self, host: str, port: int = 0, family: int = socket.AF_INET - ) -> List[Dict[str, Any]]: - try: - resp = await self._resolver.gethostbyname(host, family) - except aiodns.error.DNSError as exc: - msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" - raise OSError(msg) from exc - hosts = [] - for address in resp.addresses: - hosts.append( - { - "hostname": host, - "host": address, - "port": port, - "family": family, - "proto": 0, - "flags": socket.AI_NUMERICHOST | socket.AI_NUMERICSERV, - } - ) - - if not hosts: - raise OSError("DNS lookup failed") - - return hosts - - async def _resolve_with_query( - self, host: str, port: int = 0, family: int = socket.AF_INET - ) -> List[Dict[str, Any]]: - if family == socket.AF_INET6: - qtype = "AAAA" - else: - qtype = "A" - - try: - resp = await self._resolver.query(host, qtype) - except aiodns.error.DNSError as exc: - msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" - raise OSError(msg) from exc - - hosts = [] - for rr in resp: - hosts.append( - { - "hostname": host, - "host": rr.host, - "port": port, - "family": family, - "proto": 0, - "flags": socket.AI_NUMERICHOST, - } - ) - - if not hosts: - raise OSError("DNS lookup failed") - - return hosts - - async def close(self) -> None: - self._resolver.cancel() - - -_DefaultType = Type[Union[AsyncResolver, ThreadedResolver]] -DefaultResolver: _DefaultType = AsyncResolver if aiodns_default else ThreadedResolver diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/bson/objectid.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/bson/objectid.py deleted file mode 100644 index d3afe3cd3cd95243bd3bb5b72f1e80cf7e45921d..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/bson/objectid.py +++ /dev/null @@ -1,281 +0,0 @@ -# Copyright 2009-2015 MongoDB, Inc. -# -# 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. - -"""Tools for working with MongoDB ObjectIds.""" - -import binascii -import calendar -import datetime -import os -import struct -import threading -import time -from random import SystemRandom -from typing import Any, NoReturn, Optional, Type, Union - -from bson.errors import InvalidId -from bson.tz_util import utc - -_MAX_COUNTER_VALUE = 0xFFFFFF - - -def _raise_invalid_id(oid: str) -> NoReturn: - raise InvalidId( - "%r is not a valid ObjectId, it must be a 12-byte input" - " or a 24-character hex string" % oid - ) - - -def _random_bytes() -> bytes: - """Get the 5-byte random field of an ObjectId.""" - return os.urandom(5) - - -class ObjectId: - """A MongoDB ObjectId.""" - - _pid = os.getpid() - - _inc = SystemRandom().randint(0, _MAX_COUNTER_VALUE) - _inc_lock = threading.Lock() - - __random = _random_bytes() - - __slots__ = ("__id",) - - _type_marker = 7 - - def __init__(self, oid: Optional[Union[str, "ObjectId", bytes]] = None) -> None: - """Initialize a new ObjectId. - - An ObjectId is a 12-byte unique identifier consisting of: - - - a 4-byte value representing the seconds since the Unix epoch, - - a 5-byte random value, - - a 3-byte counter, starting with a random value. - - By default, ``ObjectId()`` creates a new unique identifier. The - optional parameter `oid` can be an :class:`ObjectId`, or any 12 - :class:`bytes`. - - For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId - specification but they are acceptable input:: - - >>> ObjectId(b'foo-bar-quux') - ObjectId('666f6f2d6261722d71757578') - - `oid` can also be a :class:`str` of 24 hex digits:: - - >>> ObjectId('0123456789ab0123456789ab') - ObjectId('0123456789ab0123456789ab') - - Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor - 24 hex digits, or :class:`TypeError` if `oid` is not an accepted type. - - :Parameters: - - `oid` (optional): a valid ObjectId. - - .. seealso:: The MongoDB documentation on `ObjectIds `_. - - .. versionchanged:: 3.8 - :class:`~bson.objectid.ObjectId` now implements the `ObjectID - specification version 0.2 - `_. - """ - if oid is None: - self.__generate() - elif isinstance(oid, bytes) and len(oid) == 12: - self.__id = oid - else: - self.__validate(oid) - - @classmethod - def from_datetime(cls: Type["ObjectId"], generation_time: datetime.datetime) -> "ObjectId": - """Create a dummy ObjectId instance with a specific generation time. - - This method is useful for doing range queries on a field - containing :class:`ObjectId` instances. - - .. warning:: - It is not safe to insert a document containing an ObjectId - generated using this method. This method deliberately - eliminates the uniqueness guarantee that ObjectIds - generally provide. ObjectIds generated with this method - should be used exclusively in queries. - - `generation_time` will be converted to UTC. Naive datetime - instances will be treated as though they already contain UTC. - - An example using this helper to get documents where ``"_id"`` - was generated before January 1, 2010 would be: - - >>> gen_time = datetime.datetime(2010, 1, 1) - >>> dummy_id = ObjectId.from_datetime(gen_time) - >>> result = collection.find({"_id": {"$lt": dummy_id}}) - - :Parameters: - - `generation_time`: :class:`~datetime.datetime` to be used - as the generation time for the resulting ObjectId. - """ - offset = generation_time.utcoffset() - if offset is not None: - generation_time = generation_time - offset - timestamp = calendar.timegm(generation_time.timetuple()) - oid = struct.pack(">I", int(timestamp)) + b"\x00\x00\x00\x00\x00\x00\x00\x00" - return cls(oid) - - @classmethod - def is_valid(cls: Type["ObjectId"], oid: Any) -> bool: - """Checks if a `oid` string is valid or not. - - :Parameters: - - `oid`: the object id to validate - - .. versionadded:: 2.3 - """ - if not oid: - return False - - try: - ObjectId(oid) - return True - except (InvalidId, TypeError): - return False - - @classmethod - def _random(cls) -> bytes: - """Generate a 5-byte random number once per process.""" - pid = os.getpid() - if pid != cls._pid: - cls._pid = pid - cls.__random = _random_bytes() - return cls.__random - - def __generate(self) -> None: - """Generate a new value for this ObjectId.""" - # 4 bytes current time - oid = struct.pack(">I", int(time.time())) - - # 5 bytes random - oid += ObjectId._random() - - # 3 bytes inc - with ObjectId._inc_lock: - oid += struct.pack(">I", ObjectId._inc)[1:4] - ObjectId._inc = (ObjectId._inc + 1) % (_MAX_COUNTER_VALUE + 1) - - self.__id = oid - - def __validate(self, oid: Any) -> None: - """Validate and use the given id for this ObjectId. - - Raises TypeError if id is not an instance of :class:`str`, - :class:`bytes`, or ObjectId. Raises InvalidId if it is not a - valid ObjectId. - - :Parameters: - - `oid`: a valid ObjectId - """ - if isinstance(oid, ObjectId): - self.__id = oid.binary - elif isinstance(oid, str): - if len(oid) == 24: - try: - self.__id = bytes.fromhex(oid) - except (TypeError, ValueError): - _raise_invalid_id(oid) - else: - _raise_invalid_id(oid) - else: - raise TypeError(f"id must be an instance of (bytes, str, ObjectId), not {type(oid)}") - - @property - def binary(self) -> bytes: - """12-byte binary representation of this ObjectId.""" - return self.__id - - @property - def generation_time(self) -> datetime.datetime: - """A :class:`datetime.datetime` instance representing the time of - generation for this :class:`ObjectId`. - - The :class:`datetime.datetime` is timezone aware, and - represents the generation time in UTC. It is precise to the - second. - """ - timestamp = struct.unpack(">I", self.__id[0:4])[0] - return datetime.datetime.fromtimestamp(timestamp, utc) - - def __getstate__(self) -> bytes: - """Return value of object for pickling. - needed explicitly because __slots__() defined. - """ - return self.__id - - def __setstate__(self, value: Any) -> None: - """Explicit state set from pickling""" - # Provide backwards compatibility with OIDs - # pickled with pymongo-1.9 or older. - if isinstance(value, dict): - oid = value["_ObjectId__id"] - else: - oid = value - # ObjectIds pickled in python 2.x used `str` for __id. - # In python 3.x this has to be converted to `bytes` - # by encoding latin-1. - if isinstance(oid, str): - self.__id = oid.encode("latin-1") - else: - self.__id = oid - - def __str__(self) -> str: - return binascii.hexlify(self.__id).decode() - - def __repr__(self) -> str: - return f"ObjectId('{str(self)}')" - - def __eq__(self, other: Any) -> bool: - if isinstance(other, ObjectId): - return self.__id == other.binary - return NotImplemented - - def __ne__(self, other: Any) -> bool: - if isinstance(other, ObjectId): - return self.__id != other.binary - return NotImplemented - - def __lt__(self, other: Any) -> bool: - if isinstance(other, ObjectId): - return self.__id < other.binary - return NotImplemented - - def __le__(self, other: Any) -> bool: - if isinstance(other, ObjectId): - return self.__id <= other.binary - return NotImplemented - - def __gt__(self, other: Any) -> bool: - if isinstance(other, ObjectId): - return self.__id > other.binary - return NotImplemented - - def __ge__(self, other: Any) -> bool: - if isinstance(other, ObjectId): - return self.__id >= other.binary - return NotImplemented - - def __hash__(self) -> int: - """Get a hash value for this :class:`ObjectId`.""" - return hash(self.__id) diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/dateutil/tz/tz.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/dateutil/tz/tz.py deleted file mode 100644 index c67f56d4659f17aab4540dfd42511bb850871a77..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/dateutil/tz/tz.py +++ /dev/null @@ -1,1849 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers timezone implementations subclassing the abstract -:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format -files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, -etc), TZ environment string (in all known formats), given ranges (with help -from relative deltas), local machine timezone, fixed offset timezone, and UTC -timezone. -""" -import datetime -import struct -import time -import sys -import os -import bisect -import weakref -from collections import OrderedDict - -import six -from six import string_types -from six.moves import _thread -from ._common import tzname_in_python2, _tzinfo -from ._common import tzrangebase, enfold -from ._common import _validate_fromutc_inputs - -from ._factories import _TzSingleton, _TzOffsetFactory -from ._factories import _TzStrFactory -try: - from .win import tzwin, tzwinlocal -except ImportError: - tzwin = tzwinlocal = None - -# For warning about rounding tzinfo -from warnings import warn - -ZERO = datetime.timedelta(0) -EPOCH = datetime.datetime.utcfromtimestamp(0) -EPOCHORDINAL = EPOCH.toordinal() - - -@six.add_metaclass(_TzSingleton) -class tzutc(datetime.tzinfo): - """ - This is a tzinfo object that represents the UTC time zone. - - **Examples:** - - .. doctest:: - - >>> from datetime import * - >>> from dateutil.tz import * - - >>> datetime.now() - datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) - - >>> datetime.now(tzutc()) - datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) - - >>> datetime.now(tzutc()).tzname() - 'UTC' - - .. versionchanged:: 2.7.0 - ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will - always return the same object. - - .. doctest:: - - >>> from dateutil.tz import tzutc, UTC - >>> tzutc() is tzutc() - True - >>> tzutc() is UTC - True - """ - def utcoffset(self, dt): - return ZERO - - def dst(self, dt): - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return "UTC" - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - return False - - @_validate_fromutc_inputs - def fromutc(self, dt): - """ - Fast track version of fromutc() returns the original ``dt`` object for - any valid :py:class:`datetime.datetime` object. - """ - return dt - - def __eq__(self, other): - if not isinstance(other, (tzutc, tzoffset)): - return NotImplemented - - return (isinstance(other, tzutc) or - (isinstance(other, tzoffset) and other._offset == ZERO)) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s()" % self.__class__.__name__ - - __reduce__ = object.__reduce__ - - -#: Convenience constant providing a :class:`tzutc()` instance -#: -#: .. versionadded:: 2.7.0 -UTC = tzutc() - - -@six.add_metaclass(_TzOffsetFactory) -class tzoffset(datetime.tzinfo): - """ - A simple class for representing a fixed offset from UTC. - - :param name: - The timezone name, to be returned when ``tzname()`` is called. - :param offset: - The time zone offset in seconds, or (since version 2.6.0, represented - as a :py:class:`datetime.timedelta` object). - """ - def __init__(self, name, offset): - self._name = name - - try: - # Allow a timedelta - offset = offset.total_seconds() - except (TypeError, AttributeError): - pass - - self._offset = datetime.timedelta(seconds=_get_supported_offset(offset)) - - def utcoffset(self, dt): - return self._offset - - def dst(self, dt): - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._name - - @_validate_fromutc_inputs - def fromutc(self, dt): - return dt + self._offset - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - return False - - def __eq__(self, other): - if not isinstance(other, tzoffset): - return NotImplemented - - return self._offset == other._offset - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(%s, %s)" % (self.__class__.__name__, - repr(self._name), - int(self._offset.total_seconds())) - - __reduce__ = object.__reduce__ - - -class tzlocal(_tzinfo): - """ - A :class:`tzinfo` subclass built around the ``time`` timezone functions. - """ - def __init__(self): - super(tzlocal, self).__init__() - - self._std_offset = datetime.timedelta(seconds=-time.timezone) - if time.daylight: - self._dst_offset = datetime.timedelta(seconds=-time.altzone) - else: - self._dst_offset = self._std_offset - - self._dst_saved = self._dst_offset - self._std_offset - self._hasdst = bool(self._dst_saved) - self._tznames = tuple(time.tzname) - - def utcoffset(self, dt): - if dt is None and self._hasdst: - return None - - if self._isdst(dt): - return self._dst_offset - else: - return self._std_offset - - def dst(self, dt): - if dt is None and self._hasdst: - return None - - if self._isdst(dt): - return self._dst_offset - self._std_offset - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._tznames[self._isdst(dt)] - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - naive_dst = self._naive_is_dst(dt) - return (not naive_dst and - (naive_dst != self._naive_is_dst(dt - self._dst_saved))) - - def _naive_is_dst(self, dt): - timestamp = _datetime_to_timestamp(dt) - return time.localtime(timestamp + time.timezone).tm_isdst - - def _isdst(self, dt, fold_naive=True): - # We can't use mktime here. It is unstable when deciding if - # the hour near to a change is DST or not. - # - # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, - # dt.minute, dt.second, dt.weekday(), 0, -1)) - # return time.localtime(timestamp).tm_isdst - # - # The code above yields the following result: - # - # >>> import tz, datetime - # >>> t = tz.tzlocal() - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRDT' - # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() - # 'BRST' - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRST' - # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() - # 'BRDT' - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRDT' - # - # Here is a more stable implementation: - # - if not self._hasdst: - return False - - # Check for ambiguous times: - dstval = self._naive_is_dst(dt) - fold = getattr(dt, 'fold', None) - - if self.is_ambiguous(dt): - if fold is not None: - return not self._fold(dt) - else: - return True - - return dstval - - def __eq__(self, other): - if isinstance(other, tzlocal): - return (self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset) - elif isinstance(other, tzutc): - return (not self._hasdst and - self._tznames[0] in {'UTC', 'GMT'} and - self._std_offset == ZERO) - elif isinstance(other, tzoffset): - return (not self._hasdst and - self._tznames[0] == other._name and - self._std_offset == other._offset) - else: - return NotImplemented - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s()" % self.__class__.__name__ - - __reduce__ = object.__reduce__ - - -class _ttinfo(object): - __slots__ = ["offset", "delta", "isdst", "abbr", - "isstd", "isgmt", "dstoffset"] - - def __init__(self): - for attr in self.__slots__: - setattr(self, attr, None) - - def __repr__(self): - l = [] - for attr in self.__slots__: - value = getattr(self, attr) - if value is not None: - l.append("%s=%s" % (attr, repr(value))) - return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) - - def __eq__(self, other): - if not isinstance(other, _ttinfo): - return NotImplemented - - return (self.offset == other.offset and - self.delta == other.delta and - self.isdst == other.isdst and - self.abbr == other.abbr and - self.isstd == other.isstd and - self.isgmt == other.isgmt and - self.dstoffset == other.dstoffset) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __getstate__(self): - state = {} - for name in self.__slots__: - state[name] = getattr(self, name, None) - return state - - def __setstate__(self, state): - for name in self.__slots__: - if name in state: - setattr(self, name, state[name]) - - -class _tzfile(object): - """ - Lightweight class for holding the relevant transition and time zone - information read from binary tzfiles. - """ - attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list', - 'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first'] - - def __init__(self, **kwargs): - for attr in self.attrs: - setattr(self, attr, kwargs.get(attr, None)) - - -class tzfile(_tzinfo): - """ - This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` - format timezone files to extract current and historical zone information. - - :param fileobj: - This can be an opened file stream or a file name that the time zone - information can be read from. - - :param filename: - This is an optional parameter specifying the source of the time zone - information in the event that ``fileobj`` is a file object. If omitted - and ``fileobj`` is a file stream, this parameter will be set either to - ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. - - See `Sources for Time Zone and Daylight Saving Time Data - `_ for more information. - Time zone files can be compiled from the `IANA Time Zone database files - `_ with the `zic time zone compiler - `_ - - .. note:: - - Only construct a ``tzfile`` directly if you have a specific timezone - file on disk that you want to read into a Python ``tzinfo`` object. - If you want to get a ``tzfile`` representing a specific IANA zone, - (e.g. ``'America/New_York'``), you should call - :func:`dateutil.tz.gettz` with the zone identifier. - - - **Examples:** - - Using the US Eastern time zone as an example, we can see that a ``tzfile`` - provides time zone information for the standard Daylight Saving offsets: - - .. testsetup:: tzfile - - from dateutil.tz import gettz - from datetime import datetime - - .. doctest:: tzfile - - >>> NYC = gettz('America/New_York') - >>> NYC - tzfile('/usr/share/zoneinfo/America/New_York') - - >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST - 2016-01-03 00:00:00-05:00 - - >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT - 2016-07-07 00:00:00-04:00 - - - The ``tzfile`` structure contains a fully history of the time zone, - so historical dates will also have the right offsets. For example, before - the adoption of the UTC standards, New York used local solar mean time: - - .. doctest:: tzfile - - >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT - 1901-04-12 00:00:00-04:56 - - And during World War II, New York was on "Eastern War Time", which was a - state of permanent daylight saving time: - - .. doctest:: tzfile - - >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT - 1944-02-07 00:00:00-04:00 - - """ - - def __init__(self, fileobj, filename=None): - super(tzfile, self).__init__() - - file_opened_here = False - if isinstance(fileobj, string_types): - self._filename = fileobj - fileobj = open(fileobj, 'rb') - file_opened_here = True - elif filename is not None: - self._filename = filename - elif hasattr(fileobj, "name"): - self._filename = fileobj.name - else: - self._filename = repr(fileobj) - - if fileobj is not None: - if not file_opened_here: - fileobj = _nullcontext(fileobj) - - with fileobj as file_stream: - tzobj = self._read_tzfile(file_stream) - - self._set_tzdata(tzobj) - - def _set_tzdata(self, tzobj): - """ Set the time zone data of this object from a _tzfile object """ - # Copy the relevant attributes over as private attributes - for attr in _tzfile.attrs: - setattr(self, '_' + attr, getattr(tzobj, attr)) - - def _read_tzfile(self, fileobj): - out = _tzfile() - - # From tzfile(5): - # - # The time zone information files used by tzset(3) - # begin with the magic characters "TZif" to identify - # them as time zone information files, followed by - # sixteen bytes reserved for future use, followed by - # six four-byte values of type long, written in a - # ``standard'' byte order (the high-order byte - # of the value is written first). - if fileobj.read(4).decode() != "TZif": - raise ValueError("magic not found") - - fileobj.read(16) - - ( - # The number of UTC/local indicators stored in the file. - ttisgmtcnt, - - # The number of standard/wall indicators stored in the file. - ttisstdcnt, - - # The number of leap seconds for which data is - # stored in the file. - leapcnt, - - # The number of "transition times" for which data - # is stored in the file. - timecnt, - - # The number of "local time types" for which data - # is stored in the file (must not be zero). - typecnt, - - # The number of characters of "time zone - # abbreviation strings" stored in the file. - charcnt, - - ) = struct.unpack(">6l", fileobj.read(24)) - - # The above header is followed by tzh_timecnt four-byte - # values of type long, sorted in ascending order. - # These values are written in ``standard'' byte order. - # Each is used as a transition time (as returned by - # time(2)) at which the rules for computing local time - # change. - - if timecnt: - out.trans_list_utc = list(struct.unpack(">%dl" % timecnt, - fileobj.read(timecnt*4))) - else: - out.trans_list_utc = [] - - # Next come tzh_timecnt one-byte values of type unsigned - # char; each one tells which of the different types of - # ``local time'' types described in the file is associated - # with the same-indexed transition time. These values - # serve as indices into an array of ttinfo structures that - # appears next in the file. - - if timecnt: - out.trans_idx = struct.unpack(">%dB" % timecnt, - fileobj.read(timecnt)) - else: - out.trans_idx = [] - - # Each ttinfo structure is written as a four-byte value - # for tt_gmtoff of type long, in a standard byte - # order, followed by a one-byte value for tt_isdst - # and a one-byte value for tt_abbrind. In each - # structure, tt_gmtoff gives the number of - # seconds to be added to UTC, tt_isdst tells whether - # tm_isdst should be set by localtime(3), and - # tt_abbrind serves as an index into the array of - # time zone abbreviation characters that follow the - # ttinfo structure(s) in the file. - - ttinfo = [] - - for i in range(typecnt): - ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) - - abbr = fileobj.read(charcnt).decode() - - # Then there are tzh_leapcnt pairs of four-byte - # values, written in standard byte order; the - # first value of each pair gives the time (as - # returned by time(2)) at which a leap second - # occurs; the second gives the total number of - # leap seconds to be applied after the given time. - # The pairs of values are sorted in ascending order - # by time. - - # Not used, for now (but seek for correct file position) - if leapcnt: - fileobj.seek(leapcnt * 8, os.SEEK_CUR) - - # Then there are tzh_ttisstdcnt standard/wall - # indicators, each stored as a one-byte value; - # they tell whether the transition times associated - # with local time types were specified as standard - # time or wall clock time, and are used when - # a time zone file is used in handling POSIX-style - # time zone environment variables. - - if ttisstdcnt: - isstd = struct.unpack(">%db" % ttisstdcnt, - fileobj.read(ttisstdcnt)) - - # Finally, there are tzh_ttisgmtcnt UTC/local - # indicators, each stored as a one-byte value; - # they tell whether the transition times associated - # with local time types were specified as UTC or - # local time, and are used when a time zone file - # is used in handling POSIX-style time zone envi- - # ronment variables. - - if ttisgmtcnt: - isgmt = struct.unpack(">%db" % ttisgmtcnt, - fileobj.read(ttisgmtcnt)) - - # Build ttinfo list - out.ttinfo_list = [] - for i in range(typecnt): - gmtoff, isdst, abbrind = ttinfo[i] - gmtoff = _get_supported_offset(gmtoff) - tti = _ttinfo() - tti.offset = gmtoff - tti.dstoffset = datetime.timedelta(0) - tti.delta = datetime.timedelta(seconds=gmtoff) - tti.isdst = isdst - tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] - tti.isstd = (ttisstdcnt > i and isstd[i] != 0) - tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) - out.ttinfo_list.append(tti) - - # Replace ttinfo indexes for ttinfo objects. - out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx] - - # Set standard, dst, and before ttinfos. before will be - # used when a given time is before any transitions, - # and will be set to the first non-dst ttinfo, or to - # the first dst, if all of them are dst. - out.ttinfo_std = None - out.ttinfo_dst = None - out.ttinfo_before = None - if out.ttinfo_list: - if not out.trans_list_utc: - out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0] - else: - for i in range(timecnt-1, -1, -1): - tti = out.trans_idx[i] - if not out.ttinfo_std and not tti.isdst: - out.ttinfo_std = tti - elif not out.ttinfo_dst and tti.isdst: - out.ttinfo_dst = tti - - if out.ttinfo_std and out.ttinfo_dst: - break - else: - if out.ttinfo_dst and not out.ttinfo_std: - out.ttinfo_std = out.ttinfo_dst - - for tti in out.ttinfo_list: - if not tti.isdst: - out.ttinfo_before = tti - break - else: - out.ttinfo_before = out.ttinfo_list[0] - - # Now fix transition times to become relative to wall time. - # - # I'm not sure about this. In my tests, the tz source file - # is setup to wall time, and in the binary file isstd and - # isgmt are off, so it should be in wall time. OTOH, it's - # always in gmt time. Let me know if you have comments - # about this. - lastdst = None - lastoffset = None - lastdstoffset = None - lastbaseoffset = None - out.trans_list = [] - - for i, tti in enumerate(out.trans_idx): - offset = tti.offset - dstoffset = 0 - - if lastdst is not None: - if tti.isdst: - if not lastdst: - dstoffset = offset - lastoffset - - if not dstoffset and lastdstoffset: - dstoffset = lastdstoffset - - tti.dstoffset = datetime.timedelta(seconds=dstoffset) - lastdstoffset = dstoffset - - # If a time zone changes its base offset during a DST transition, - # then you need to adjust by the previous base offset to get the - # transition time in local time. Otherwise you use the current - # base offset. Ideally, I would have some mathematical proof of - # why this is true, but I haven't really thought about it enough. - baseoffset = offset - dstoffset - adjustment = baseoffset - if (lastbaseoffset is not None and baseoffset != lastbaseoffset - and tti.isdst != lastdst): - # The base DST has changed - adjustment = lastbaseoffset - - lastdst = tti.isdst - lastoffset = offset - lastbaseoffset = baseoffset - - out.trans_list.append(out.trans_list_utc[i] + adjustment) - - out.trans_idx = tuple(out.trans_idx) - out.trans_list = tuple(out.trans_list) - out.trans_list_utc = tuple(out.trans_list_utc) - - return out - - def _find_last_transition(self, dt, in_utc=False): - # If there's no list, there are no transitions to find - if not self._trans_list: - return None - - timestamp = _datetime_to_timestamp(dt) - - # Find where the timestamp fits in the transition list - if the - # timestamp is a transition time, it's part of the "after" period. - trans_list = self._trans_list_utc if in_utc else self._trans_list - idx = bisect.bisect_right(trans_list, timestamp) - - # We want to know when the previous transition was, so subtract off 1 - return idx - 1 - - def _get_ttinfo(self, idx): - # For no list or after the last transition, default to _ttinfo_std - if idx is None or (idx + 1) >= len(self._trans_list): - return self._ttinfo_std - - # If there is a list and the time is before it, return _ttinfo_before - if idx < 0: - return self._ttinfo_before - - return self._trans_idx[idx] - - def _find_ttinfo(self, dt): - idx = self._resolve_ambiguous_time(dt) - - return self._get_ttinfo(idx) - - def fromutc(self, dt): - """ - The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. - - :param dt: - A :py:class:`datetime.datetime` object. - - :raises TypeError: - Raised if ``dt`` is not a :py:class:`datetime.datetime` object. - - :raises ValueError: - Raised if this is called with a ``dt`` which does not have this - ``tzinfo`` attached. - - :return: - Returns a :py:class:`datetime.datetime` object representing the - wall time in ``self``'s time zone. - """ - # These isinstance checks are in datetime.tzinfo, so we'll preserve - # them, even if we don't care about duck typing. - if not isinstance(dt, datetime.datetime): - raise TypeError("fromutc() requires a datetime argument") - - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - # First treat UTC as wall time and get the transition we're in. - idx = self._find_last_transition(dt, in_utc=True) - tti = self._get_ttinfo(idx) - - dt_out = dt + datetime.timedelta(seconds=tti.offset) - - fold = self.is_ambiguous(dt_out, idx=idx) - - return enfold(dt_out, fold=int(fold)) - - def is_ambiguous(self, dt, idx=None): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - if idx is None: - idx = self._find_last_transition(dt) - - # Calculate the difference in offsets from current to previous - timestamp = _datetime_to_timestamp(dt) - tti = self._get_ttinfo(idx) - - if idx is None or idx <= 0: - return False - - od = self._get_ttinfo(idx - 1).offset - tti.offset - tt = self._trans_list[idx] # Transition time - - return timestamp < tt + od - - def _resolve_ambiguous_time(self, dt): - idx = self._find_last_transition(dt) - - # If we have no transitions, return the index - _fold = self._fold(dt) - if idx is None or idx == 0: - return idx - - # If it's ambiguous and we're in a fold, shift to a different index. - idx_offset = int(not _fold and self.is_ambiguous(dt, idx)) - - return idx - idx_offset - - def utcoffset(self, dt): - if dt is None: - return None - - if not self._ttinfo_std: - return ZERO - - return self._find_ttinfo(dt).delta - - def dst(self, dt): - if dt is None: - return None - - if not self._ttinfo_dst: - return ZERO - - tti = self._find_ttinfo(dt) - - if not tti.isdst: - return ZERO - - # The documentation says that utcoffset()-dst() must - # be constant for every dt. - return tti.dstoffset - - @tzname_in_python2 - def tzname(self, dt): - if not self._ttinfo_std or dt is None: - return None - return self._find_ttinfo(dt).abbr - - def __eq__(self, other): - if not isinstance(other, tzfile): - return NotImplemented - return (self._trans_list == other._trans_list and - self._trans_idx == other._trans_idx and - self._ttinfo_list == other._ttinfo_list) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) - - def __reduce__(self): - return self.__reduce_ex__(None) - - def __reduce_ex__(self, protocol): - return (self.__class__, (None, self._filename), self.__dict__) - - -class tzrange(tzrangebase): - """ - The ``tzrange`` object is a time zone specified by a set of offsets and - abbreviations, equivalent to the way the ``TZ`` variable can be specified - in POSIX-like systems, but using Python delta objects to specify DST - start, end and offsets. - - :param stdabbr: - The abbreviation for standard time (e.g. ``'EST'``). - - :param stdoffset: - An integer or :class:`datetime.timedelta` object or equivalent - specifying the base offset from UTC. - - If unspecified, +00:00 is used. - - :param dstabbr: - The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). - - If specified, with no other DST information, DST is assumed to occur - and the default behavior or ``dstoffset``, ``start`` and ``end`` is - used. If unspecified and no other DST information is specified, it - is assumed that this zone has no DST. - - If this is unspecified and other DST information is *is* specified, - DST occurs in the zone but the time zone abbreviation is left - unchanged. - - :param dstoffset: - A an integer or :class:`datetime.timedelta` object or equivalent - specifying the UTC offset during DST. If unspecified and any other DST - information is specified, it is assumed to be the STD offset +1 hour. - - :param start: - A :class:`relativedelta.relativedelta` object or equivalent specifying - the time and time of year that daylight savings time starts. To - specify, for example, that DST starts at 2AM on the 2nd Sunday in - March, pass: - - ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` - - If unspecified and any other DST information is specified, the default - value is 2 AM on the first Sunday in April. - - :param end: - A :class:`relativedelta.relativedelta` object or equivalent - representing the time and time of year that daylight savings time - ends, with the same specification method as in ``start``. One note is - that this should point to the first time in the *standard* zone, so if - a transition occurs at 2AM in the DST zone and the clocks are set back - 1 hour to 1AM, set the ``hours`` parameter to +1. - - - **Examples:** - - .. testsetup:: tzrange - - from dateutil.tz import tzrange, tzstr - - .. doctest:: tzrange - - >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") - True - - >>> from dateutil.relativedelta import * - >>> range1 = tzrange("EST", -18000, "EDT") - >>> range2 = tzrange("EST", -18000, "EDT", -14400, - ... relativedelta(hours=+2, month=4, day=1, - ... weekday=SU(+1)), - ... relativedelta(hours=+1, month=10, day=31, - ... weekday=SU(-1))) - >>> tzstr('EST5EDT') == range1 == range2 - True - - """ - def __init__(self, stdabbr, stdoffset=None, - dstabbr=None, dstoffset=None, - start=None, end=None): - - global relativedelta - from dateutil import relativedelta - - self._std_abbr = stdabbr - self._dst_abbr = dstabbr - - try: - stdoffset = stdoffset.total_seconds() - except (TypeError, AttributeError): - pass - - try: - dstoffset = dstoffset.total_seconds() - except (TypeError, AttributeError): - pass - - if stdoffset is not None: - self._std_offset = datetime.timedelta(seconds=stdoffset) - else: - self._std_offset = ZERO - - if dstoffset is not None: - self._dst_offset = datetime.timedelta(seconds=dstoffset) - elif dstabbr and stdoffset is not None: - self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) - else: - self._dst_offset = ZERO - - if dstabbr and start is None: - self._start_delta = relativedelta.relativedelta( - hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) - else: - self._start_delta = start - - if dstabbr and end is None: - self._end_delta = relativedelta.relativedelta( - hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) - else: - self._end_delta = end - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = bool(self._start_delta) - - def transitions(self, year): - """ - For a given year, get the DST on and off transition times, expressed - always on the standard time side. For zones with no transitions, this - function returns ``None``. - - :param year: - The year whose transitions you would like to query. - - :return: - Returns a :class:`tuple` of :class:`datetime.datetime` objects, - ``(dston, dstoff)`` for zones with an annual DST transition, or - ``None`` for fixed offset zones. - """ - if not self.hasdst: - return None - - base_year = datetime.datetime(year, 1, 1) - - start = base_year + self._start_delta - end = base_year + self._end_delta - - return (start, end) - - def __eq__(self, other): - if not isinstance(other, tzrange): - return NotImplemented - - return (self._std_abbr == other._std_abbr and - self._dst_abbr == other._dst_abbr and - self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset and - self._start_delta == other._start_delta and - self._end_delta == other._end_delta) - - @property - def _dst_base_offset(self): - return self._dst_base_offset_ - - -@six.add_metaclass(_TzStrFactory) -class tzstr(tzrange): - """ - ``tzstr`` objects are time zone objects specified by a time-zone string as - it would be passed to a ``TZ`` variable on POSIX-style systems (see - the `GNU C Library: TZ Variable`_ for more details). - - There is one notable exception, which is that POSIX-style time zones use an - inverted offset format, so normally ``GMT+3`` would be parsed as an offset - 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an - offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX - behavior, pass a ``True`` value to ``posix_offset``. - - The :class:`tzrange` object provides the same functionality, but is - specified using :class:`relativedelta.relativedelta` objects. rather than - strings. - - :param s: - A time zone string in ``TZ`` variable format. This can be a - :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: - :class:`unicode`) or a stream emitting unicode characters - (e.g. :class:`StringIO`). - - :param posix_offset: - Optional. If set to ``True``, interpret strings such as ``GMT+3`` or - ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the - POSIX standard. - - .. caution:: - - Prior to version 2.7.0, this function also supported time zones - in the format: - - * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` - * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` - - This format is non-standard and has been deprecated; this function - will raise a :class:`DeprecatedTZFormatWarning` until - support is removed in a future version. - - .. _`GNU C Library: TZ Variable`: - https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html - """ - def __init__(self, s, posix_offset=False): - global parser - from dateutil.parser import _parser as parser - - self._s = s - - res = parser._parsetz(s) - if res is None or res.any_unused_tokens: - raise ValueError("unknown string format") - - # Here we break the compatibility with the TZ variable handling. - # GMT-3 actually *means* the timezone -3. - if res.stdabbr in ("GMT", "UTC") and not posix_offset: - res.stdoffset *= -1 - - # We must initialize it first, since _delta() needs - # _std_offset and _dst_offset set. Use False in start/end - # to avoid building it two times. - tzrange.__init__(self, res.stdabbr, res.stdoffset, - res.dstabbr, res.dstoffset, - start=False, end=False) - - if not res.dstabbr: - self._start_delta = None - self._end_delta = None - else: - self._start_delta = self._delta(res.start) - if self._start_delta: - self._end_delta = self._delta(res.end, isend=1) - - self.hasdst = bool(self._start_delta) - - def _delta(self, x, isend=0): - from dateutil import relativedelta - kwargs = {} - if x.month is not None: - kwargs["month"] = x.month - if x.weekday is not None: - kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) - if x.week > 0: - kwargs["day"] = 1 - else: - kwargs["day"] = 31 - elif x.day: - kwargs["day"] = x.day - elif x.yday is not None: - kwargs["yearday"] = x.yday - elif x.jyday is not None: - kwargs["nlyearday"] = x.jyday - if not kwargs: - # Default is to start on first sunday of april, and end - # on last sunday of october. - if not isend: - kwargs["month"] = 4 - kwargs["day"] = 1 - kwargs["weekday"] = relativedelta.SU(+1) - else: - kwargs["month"] = 10 - kwargs["day"] = 31 - kwargs["weekday"] = relativedelta.SU(-1) - if x.time is not None: - kwargs["seconds"] = x.time - else: - # Default is 2AM. - kwargs["seconds"] = 7200 - if isend: - # Convert to standard time, to follow the documented way - # of working with the extra hour. See the documentation - # of the tzinfo class. - delta = self._dst_offset - self._std_offset - kwargs["seconds"] -= delta.seconds + delta.days * 86400 - return relativedelta.relativedelta(**kwargs) - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._s)) - - -class _tzicalvtzcomp(object): - def __init__(self, tzoffsetfrom, tzoffsetto, isdst, - tzname=None, rrule=None): - self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) - self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) - self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom - self.isdst = isdst - self.tzname = tzname - self.rrule = rrule - - -class _tzicalvtz(_tzinfo): - def __init__(self, tzid, comps=[]): - super(_tzicalvtz, self).__init__() - - self._tzid = tzid - self._comps = comps - self._cachedate = [] - self._cachecomp = [] - self._cache_lock = _thread.allocate_lock() - - def _find_comp(self, dt): - if len(self._comps) == 1: - return self._comps[0] - - dt = dt.replace(tzinfo=None) - - try: - with self._cache_lock: - return self._cachecomp[self._cachedate.index( - (dt, self._fold(dt)))] - except ValueError: - pass - - lastcompdt = None - lastcomp = None - - for comp in self._comps: - compdt = self._find_compdt(comp, dt) - - if compdt and (not lastcompdt or lastcompdt < compdt): - lastcompdt = compdt - lastcomp = comp - - if not lastcomp: - # RFC says nothing about what to do when a given - # time is before the first onset date. We'll look for the - # first standard component, or the first component, if - # none is found. - for comp in self._comps: - if not comp.isdst: - lastcomp = comp - break - else: - lastcomp = comp[0] - - with self._cache_lock: - self._cachedate.insert(0, (dt, self._fold(dt))) - self._cachecomp.insert(0, lastcomp) - - if len(self._cachedate) > 10: - self._cachedate.pop() - self._cachecomp.pop() - - return lastcomp - - def _find_compdt(self, comp, dt): - if comp.tzoffsetdiff < ZERO and self._fold(dt): - dt -= comp.tzoffsetdiff - - compdt = comp.rrule.before(dt, inc=True) - - return compdt - - def utcoffset(self, dt): - if dt is None: - return None - - return self._find_comp(dt).tzoffsetto - - def dst(self, dt): - comp = self._find_comp(dt) - if comp.isdst: - return comp.tzoffsetdiff - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._find_comp(dt).tzname - - def __repr__(self): - return "" % repr(self._tzid) - - __reduce__ = object.__reduce__ - - -class tzical(object): - """ - This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure - as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. - - :param `fileobj`: - A file or stream in iCalendar format, which should be UTF-8 encoded - with CRLF endings. - - .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 - """ - def __init__(self, fileobj): - global rrule - from dateutil import rrule - - if isinstance(fileobj, string_types): - self._s = fileobj - # ical should be encoded in UTF-8 with CRLF - fileobj = open(fileobj, 'r') - else: - self._s = getattr(fileobj, 'name', repr(fileobj)) - fileobj = _nullcontext(fileobj) - - self._vtz = {} - - with fileobj as fobj: - self._parse_rfc(fobj.read()) - - def keys(self): - """ - Retrieves the available time zones as a list. - """ - return list(self._vtz.keys()) - - def get(self, tzid=None): - """ - Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. - - :param tzid: - If there is exactly one time zone available, omitting ``tzid`` - or passing :py:const:`None` value returns it. Otherwise a valid - key (which can be retrieved from :func:`keys`) is required. - - :raises ValueError: - Raised if ``tzid`` is not specified but there are either more - or fewer than 1 zone defined. - - :returns: - Returns either a :py:class:`datetime.tzinfo` object representing - the relevant time zone or :py:const:`None` if the ``tzid`` was - not found. - """ - if tzid is None: - if len(self._vtz) == 0: - raise ValueError("no timezones defined") - elif len(self._vtz) > 1: - raise ValueError("more than one timezone available") - tzid = next(iter(self._vtz)) - - return self._vtz.get(tzid) - - def _parse_offset(self, s): - s = s.strip() - if not s: - raise ValueError("empty offset") - if s[0] in ('+', '-'): - signal = (-1, +1)[s[0] == '+'] - s = s[1:] - else: - signal = +1 - if len(s) == 4: - return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal - elif len(s) == 6: - return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal - else: - raise ValueError("invalid offset: " + s) - - def _parse_rfc(self, s): - lines = s.splitlines() - if not lines: - raise ValueError("empty string") - - # Unfold - i = 0 - while i < len(lines): - line = lines[i].rstrip() - if not line: - del lines[i] - elif i > 0 and line[0] == " ": - lines[i-1] += line[1:] - del lines[i] - else: - i += 1 - - tzid = None - comps = [] - invtz = False - comptype = None - for line in lines: - if not line: - continue - name, value = line.split(':', 1) - parms = name.split(';') - if not parms: - raise ValueError("empty property name") - name = parms[0].upper() - parms = parms[1:] - if invtz: - if name == "BEGIN": - if value in ("STANDARD", "DAYLIGHT"): - # Process component - pass - else: - raise ValueError("unknown component: "+value) - comptype = value - founddtstart = False - tzoffsetfrom = None - tzoffsetto = None - rrulelines = [] - tzname = None - elif name == "END": - if value == "VTIMEZONE": - if comptype: - raise ValueError("component not closed: "+comptype) - if not tzid: - raise ValueError("mandatory TZID not found") - if not comps: - raise ValueError( - "at least one component is needed") - # Process vtimezone - self._vtz[tzid] = _tzicalvtz(tzid, comps) - invtz = False - elif value == comptype: - if not founddtstart: - raise ValueError("mandatory DTSTART not found") - if tzoffsetfrom is None: - raise ValueError( - "mandatory TZOFFSETFROM not found") - if tzoffsetto is None: - raise ValueError( - "mandatory TZOFFSETFROM not found") - # Process component - rr = None - if rrulelines: - rr = rrule.rrulestr("\n".join(rrulelines), - compatible=True, - ignoretz=True, - cache=True) - comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, - (comptype == "DAYLIGHT"), - tzname, rr) - comps.append(comp) - comptype = None - else: - raise ValueError("invalid component end: "+value) - elif comptype: - if name == "DTSTART": - # DTSTART in VTIMEZONE takes a subset of valid RRULE - # values under RFC 5545. - for parm in parms: - if parm != 'VALUE=DATE-TIME': - msg = ('Unsupported DTSTART param in ' + - 'VTIMEZONE: ' + parm) - raise ValueError(msg) - rrulelines.append(line) - founddtstart = True - elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): - rrulelines.append(line) - elif name == "TZOFFSETFROM": - if parms: - raise ValueError( - "unsupported %s parm: %s " % (name, parms[0])) - tzoffsetfrom = self._parse_offset(value) - elif name == "TZOFFSETTO": - if parms: - raise ValueError( - "unsupported TZOFFSETTO parm: "+parms[0]) - tzoffsetto = self._parse_offset(value) - elif name == "TZNAME": - if parms: - raise ValueError( - "unsupported TZNAME parm: "+parms[0]) - tzname = value - elif name == "COMMENT": - pass - else: - raise ValueError("unsupported property: "+name) - else: - if name == "TZID": - if parms: - raise ValueError( - "unsupported TZID parm: "+parms[0]) - tzid = value - elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): - pass - else: - raise ValueError("unsupported property: "+name) - elif name == "BEGIN" and value == "VTIMEZONE": - tzid = None - comps = [] - invtz = True - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._s)) - - -if sys.platform != "win32": - TZFILES = ["/etc/localtime", "localtime"] - TZPATHS = ["/usr/share/zoneinfo", - "/usr/lib/zoneinfo", - "/usr/share/lib/zoneinfo", - "/etc/zoneinfo"] -else: - TZFILES = [] - TZPATHS = [] - - -def __get_gettz(): - tzlocal_classes = (tzlocal,) - if tzwinlocal is not None: - tzlocal_classes += (tzwinlocal,) - - class GettzFunc(object): - """ - Retrieve a time zone object from a string representation - - This function is intended to retrieve the :py:class:`tzinfo` subclass - that best represents the time zone that would be used if a POSIX - `TZ variable`_ were set to the same value. - - If no argument or an empty string is passed to ``gettz``, local time - is returned: - - .. code-block:: python3 - - >>> gettz() - tzfile('/etc/localtime') - - This function is also the preferred way to map IANA tz database keys - to :class:`tzfile` objects: - - .. code-block:: python3 - - >>> gettz('Pacific/Kiritimati') - tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') - - On Windows, the standard is extended to include the Windows-specific - zone names provided by the operating system: - - .. code-block:: python3 - - >>> gettz('Egypt Standard Time') - tzwin('Egypt Standard Time') - - Passing a GNU ``TZ`` style string time zone specification returns a - :class:`tzstr` object: - - .. code-block:: python3 - - >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') - tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') - - :param name: - A time zone name (IANA, or, on Windows, Windows keys), location of - a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone - specifier. An empty string, no argument or ``None`` is interpreted - as local time. - - :return: - Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` - subclasses. - - .. versionchanged:: 2.7.0 - - After version 2.7.0, any two calls to ``gettz`` using the same - input strings will return the same object: - - .. code-block:: python3 - - >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') - True - - In addition to improving performance, this ensures that - `"same zone" semantics`_ are used for datetimes in the same zone. - - - .. _`TZ variable`: - https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html - - .. _`"same zone" semantics`: - https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html - """ - def __init__(self): - - self.__instances = weakref.WeakValueDictionary() - self.__strong_cache_size = 8 - self.__strong_cache = OrderedDict() - self._cache_lock = _thread.allocate_lock() - - def __call__(self, name=None): - with self._cache_lock: - rv = self.__instances.get(name, None) - - if rv is None: - rv = self.nocache(name=name) - if not (name is None - or isinstance(rv, tzlocal_classes) - or rv is None): - # tzlocal is slightly more complicated than the other - # time zone providers because it depends on environment - # at construction time, so don't cache that. - # - # We also cannot store weak references to None, so we - # will also not store that. - self.__instances[name] = rv - else: - # No need for strong caching, return immediately - return rv - - self.__strong_cache[name] = self.__strong_cache.pop(name, rv) - - if len(self.__strong_cache) > self.__strong_cache_size: - self.__strong_cache.popitem(last=False) - - return rv - - def set_cache_size(self, size): - with self._cache_lock: - self.__strong_cache_size = size - while len(self.__strong_cache) > size: - self.__strong_cache.popitem(last=False) - - def cache_clear(self): - with self._cache_lock: - self.__instances = weakref.WeakValueDictionary() - self.__strong_cache.clear() - - @staticmethod - def nocache(name=None): - """A non-cached version of gettz""" - tz = None - if not name: - try: - name = os.environ["TZ"] - except KeyError: - pass - if name is None or name in ("", ":"): - for filepath in TZFILES: - if not os.path.isabs(filepath): - filename = filepath - for path in TZPATHS: - filepath = os.path.join(path, filename) - if os.path.isfile(filepath): - break - else: - continue - if os.path.isfile(filepath): - try: - tz = tzfile(filepath) - break - except (IOError, OSError, ValueError): - pass - else: - tz = tzlocal() - else: - try: - if name.startswith(":"): - name = name[1:] - except TypeError as e: - if isinstance(name, bytes): - new_msg = "gettz argument should be str, not bytes" - six.raise_from(TypeError(new_msg), e) - else: - raise - if os.path.isabs(name): - if os.path.isfile(name): - tz = tzfile(name) - else: - tz = None - else: - for path in TZPATHS: - filepath = os.path.join(path, name) - if not os.path.isfile(filepath): - filepath = filepath.replace(' ', '_') - if not os.path.isfile(filepath): - continue - try: - tz = tzfile(filepath) - break - except (IOError, OSError, ValueError): - pass - else: - tz = None - if tzwin is not None: - try: - tz = tzwin(name) - except (WindowsError, UnicodeEncodeError): - # UnicodeEncodeError is for Python 2.7 compat - tz = None - - if not tz: - from dateutil.zoneinfo import get_zonefile_instance - tz = get_zonefile_instance().get(name) - - if not tz: - for c in name: - # name is not a tzstr unless it has at least - # one offset. For short values of "name", an - # explicit for loop seems to be the fastest way - # To determine if a string contains a digit - if c in "0123456789": - try: - tz = tzstr(name) - except ValueError: - pass - break - else: - if name in ("GMT", "UTC"): - tz = UTC - elif name in time.tzname: - tz = tzlocal() - return tz - - return GettzFunc() - - -gettz = __get_gettz() -del __get_gettz - - -def datetime_exists(dt, tz=None): - """ - Given a datetime and a time zone, determine whether or not a given datetime - would fall in a gap. - - :param dt: - A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` - is provided.) - - :param tz: - A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If - ``None`` or not provided, the datetime's own time zone will be used. - - :return: - Returns a boolean value whether or not the "wall time" exists in - ``tz``. - - .. versionadded:: 2.7.0 - """ - if tz is None: - if dt.tzinfo is None: - raise ValueError('Datetime is naive and no time zone provided.') - tz = dt.tzinfo - - dt = dt.replace(tzinfo=None) - - # This is essentially a test of whether or not the datetime can survive - # a round trip to UTC. - dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz) - dt_rt = dt_rt.replace(tzinfo=None) - - return dt == dt_rt - - -def datetime_ambiguous(dt, tz=None): - """ - Given a datetime and a time zone, determine whether or not a given datetime - is ambiguous (i.e if there are two times differentiated only by their DST - status). - - :param dt: - A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` - is provided.) - - :param tz: - A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If - ``None`` or not provided, the datetime's own time zone will be used. - - :return: - Returns a boolean value whether or not the "wall time" is ambiguous in - ``tz``. - - .. versionadded:: 2.6.0 - """ - if tz is None: - if dt.tzinfo is None: - raise ValueError('Datetime is naive and no time zone provided.') - - tz = dt.tzinfo - - # If a time zone defines its own "is_ambiguous" function, we'll use that. - is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) - if is_ambiguous_fn is not None: - try: - return tz.is_ambiguous(dt) - except Exception: - pass - - # If it doesn't come out and tell us it's ambiguous, we'll just check if - # the fold attribute has any effect on this particular date and time. - dt = dt.replace(tzinfo=tz) - wall_0 = enfold(dt, fold=0) - wall_1 = enfold(dt, fold=1) - - same_offset = wall_0.utcoffset() == wall_1.utcoffset() - same_dst = wall_0.dst() == wall_1.dst() - - return not (same_offset and same_dst) - - -def resolve_imaginary(dt): - """ - Given a datetime that may be imaginary, return an existing datetime. - - This function assumes that an imaginary datetime represents what the - wall time would be in a zone had the offset transition not occurred, so - it will always fall forward by the transition's change in offset. - - .. doctest:: - - >>> from dateutil import tz - >>> from datetime import datetime - >>> NYC = tz.gettz('America/New_York') - >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) - 2017-03-12 03:30:00-04:00 - - >>> KIR = tz.gettz('Pacific/Kiritimati') - >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) - 1995-01-02 12:30:00+14:00 - - As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, - existing datetime, so a round-trip to and from UTC is sufficient to get - an extant datetime, however, this generally "falls back" to an earlier time - rather than falling forward to the STD side (though no guarantees are made - about this behavior). - - :param dt: - A :class:`datetime.datetime` which may or may not exist. - - :return: - Returns an existing :class:`datetime.datetime`. If ``dt`` was not - imaginary, the datetime returned is guaranteed to be the same object - passed to the function. - - .. versionadded:: 2.7.0 - """ - if dt.tzinfo is not None and not datetime_exists(dt): - - curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() - old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() - - dt += curr_offset - old_offset - - return dt - - -def _datetime_to_timestamp(dt): - """ - Convert a :class:`datetime.datetime` object to an epoch timestamp in - seconds since January 1, 1970, ignoring the time zone. - """ - return (dt.replace(tzinfo=None) - EPOCH).total_seconds() - - -if sys.version_info >= (3, 6): - def _get_supported_offset(second_offset): - return second_offset -else: - def _get_supported_offset(second_offset): - # For python pre-3.6, round to full-minutes if that's not the case. - # Python's datetime doesn't accept sub-minute timezones. Check - # http://python.org/sf/1447945 or https://bugs.python.org/issue5288 - # for some information. - old_offset = second_offset - calculated_offset = 60 * ((second_offset + 30) // 60) - return calculated_offset - - -try: - # Python 3.7 feature - from contextlib import nullcontext as _nullcontext -except ImportError: - class _nullcontext(object): - """ - Class for wrapping contexts so that they are passed through in a - with statement. - """ - def __init__(self, context): - self.context = context - - def __enter__(self): - return self.context - - def __exit__(*args, **kwargs): - pass - -# vim:ts=4:sw=4:et diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/keyword_table/simple_base.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/keyword_table/simple_base.py deleted file mode 100644 index 4d542c38da0d37d7504500a56ee9473f24f51eff..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/keyword_table/simple_base.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Simple keyword-table based index. - -Similar to GPTKeywordTableIndex, but uses a simpler keyword extraction -technique that doesn't involve GPT - just uses regex. - -""" - -from typing import Set - -from gpt_index.indices.keyword_table.base import BaseGPTKeywordTableIndex -from gpt_index.indices.keyword_table.utils import simple_extract_keywords -from gpt_index.prompts.default_prompts import DEFAULT_QUERY_KEYWORD_EXTRACT_TEMPLATE - -DQKET = DEFAULT_QUERY_KEYWORD_EXTRACT_TEMPLATE - - -class GPTSimpleKeywordTableIndex(BaseGPTKeywordTableIndex): - """GPT Simple Keyword Table Index. - - This index uses a simple regex extractor to extract keywords from the text. - - """ - - def _extract_keywords(self, text: str) -> Set[str]: - """Extract keywords from text.""" - return simple_extract_keywords(text, self.max_keywords_per_chunk) diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/struct_store/sql.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/struct_store/sql.py deleted file mode 100644 index ef7143053d4ed74001ce46e253b69d0e30490029..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/gpt_index/indices/struct_store/sql.py +++ /dev/null @@ -1,212 +0,0 @@ -"""SQL Structured Store.""" -import json -from typing import Any, Dict, Optional, Sequence, Type - -from sqlalchemy import Table - -from gpt_index.data_structs.table import SQLStructTable -from gpt_index.indices.base import DOCUMENTS_INPUT, BaseGPTIndex -from gpt_index.indices.common.struct_store.schema import SQLContextContainer -from gpt_index.indices.common.struct_store.sql import SQLStructDatapointExtractor -from gpt_index.indices.query.base import BaseGPTIndexQuery -from gpt_index.indices.query.schema import QueryMode -from gpt_index.indices.query.struct_store.sql import ( - GPTNLStructStoreIndexQuery, - GPTSQLStructStoreIndexQuery, -) -from gpt_index.indices.struct_store.base import BaseGPTStructStoreIndex -from gpt_index.indices.struct_store.container_builder import SQLContextContainerBuilder -from gpt_index.langchain_helpers.chain_wrapper import LLMPredictor -from gpt_index.langchain_helpers.sql_wrapper import SQLDatabase -from gpt_index.schema import BaseDocument - - -class GPTSQLStructStoreIndex(BaseGPTStructStoreIndex[SQLStructTable]): - """Base GPT SQL Struct Store Index. - - The GPTSQLStructStoreIndex is an index that uses a SQL database - under the hood. During index construction, the data can be inferred - from unstructured documents given a schema extract prompt, - or it can be pre-loaded in the database. - - During query time, the user can either specify a raw SQL query - or a natural language query to retrieve their data. - - Args: - documents (Optional[Sequence[DOCUMENTS_INPUT]]): Documents to index. - NOTE: in the SQL index, this is an optional field. - sql_database (Optional[SQLDatabase]): SQL database to use, - including table names to specify. - See :ref:`Ref-Struct-Store` for more details. - table_name (Optional[str]): Name of the table to use - for extracting data. - Either table_name or table must be specified. - table (Optional[Table]): SQLAlchemy Table object to use. - Specifying the Table object explicitly, instead of - the table name, allows you to pass in a view. - Either table_name or table must be specified. - sql_context_container (Optional[SQLContextContainer]): SQL context container. - an be generated from a SQLContextContainerBuilder. - See :ref:`Ref-Struct-Store` for more details. - - """ - - index_struct_cls = SQLStructTable - - def __init__( - self, - documents: Optional[Sequence[DOCUMENTS_INPUT]] = None, - index_struct: Optional[SQLStructTable] = None, - llm_predictor: Optional[LLMPredictor] = None, - sql_database: Optional[SQLDatabase] = None, - table_name: Optional[str] = None, - table: Optional[Table] = None, - ref_doc_id_column: Optional[str] = None, - sql_context_container: Optional[SQLContextContainer] = None, - **kwargs: Any, - ) -> None: - """Initialize params.""" - if sql_database is None: - raise ValueError("sql_database must be specified") - self.sql_database = sql_database - # needed here for data extractor - self._ref_doc_id_column = ref_doc_id_column - self._table_name = table_name - self._table = table - - # if documents aren't specified, pass in a blank [] - documents = documents or [] - - super().__init__( - documents=documents, - index_struct=index_struct, - llm_predictor=llm_predictor, - **kwargs, - ) - - # TODO: index_struct context_dict is deprecated, - # we're migrating storage of information to here. - if sql_context_container is None: - container_builder = SQLContextContainerBuilder(sql_database) - sql_context_container = container_builder.build_context_container() - self.sql_context_container = sql_context_container - - def _build_index_from_documents( - self, documents: Sequence[BaseDocument] - ) -> SQLStructTable: - """Build index from documents.""" - index_struct = self.index_struct_cls() - if len(documents) == 0: - return index_struct - else: - data_extractor = SQLStructDatapointExtractor( - self._llm_predictor, - self._text_splitter, - self.schema_extract_prompt, - self.output_parser, - self.sql_database, - table_name=self._table_name, - table=self._table, - ref_doc_id_column=self._ref_doc_id_column, - ) - for d in documents: - data_extractor.insert_datapoint_from_document(d) - return index_struct - - def _insert(self, document: BaseDocument, **insert_kwargs: Any) -> None: - """Insert a document.""" - data_extractor = SQLStructDatapointExtractor( - self._llm_predictor, - self._text_splitter, - self.schema_extract_prompt, - self.output_parser, - self.sql_database, - table_name=self._table_name, - table=self._table, - ref_doc_id_column=self._ref_doc_id_column, - ) - data_extractor.insert_datapoint_from_document(document) - - @classmethod - def get_query_map(self) -> Dict[str, Type[BaseGPTIndexQuery]]: - """Get query map.""" - return { - QueryMode.DEFAULT: GPTNLStructStoreIndexQuery, - QueryMode.SQL: GPTSQLStructStoreIndexQuery, - } - - def _preprocess_query(self, mode: QueryMode, query_kwargs: Any) -> None: - """Preprocess query. - - This allows subclasses to pass in additional query kwargs - to query, for instance arguments that are shared between the - index and the query class. By default, this does nothing. - This also allows subclasses to do validation. - - """ - super()._preprocess_query(mode, query_kwargs) - # pass along sql_database, table_name - query_kwargs["sql_database"] = self.sql_database - if "sql_context_container" not in query_kwargs: - query_kwargs["sql_context_container"] = self.sql_context_container - if mode == QueryMode.DEFAULT: - query_kwargs["ref_doc_id_column"] = self._ref_doc_id_column - - @classmethod - def load_from_string(cls, index_string: str, **kwargs: Any) -> "BaseGPTIndex": - """Load index from string (in JSON-format). - - This method loads the index from a JSON string. The index data - structure itself is preserved completely. If the index is defined over - subindices, those subindices will also be preserved (and subindices of - those subindices, etc.). - - NOTE: load_from_string should not be used for indices composed on top - of other indices. Please define a `ComposableGraph` and use - `save_to_string` and `load_from_string` on that instead. - - Args: - index_string (str): The index string (in JSON-format). - - Returns: - BaseGPTIndex: The loaded index. - - """ - # NOTE: also getting deserialized in parent class, - # figure out how to deal with later - result_dict = json.loads(index_string) - sql_context_container = SQLContextContainer.from_dict( - result_dict["sql_context_container"] - ) - result_obj = super().load_from_string( - index_string, sql_context_container=sql_context_container, **kwargs - ) - return result_obj - - def save_to_string(self, **save_kwargs: Any) -> str: - """Save to string. - - This method stores the index into a JSON string. - - NOTE: save_to_string should not be used for indices composed on top - of other indices. Please define a `ComposableGraph` and use - `save_to_string` and `load_from_string` on that instead. - - Returns: - str: The JSON string of the index. - - """ - if self.docstore.contains_index_struct( - exclude_ids=[self.index_struct.get_doc_id()] - ): - raise ValueError( - "Cannot call `save_to_string` on index if index is composed on top of " - "other indices. Please define a `ComposableGraph` and use " - "`save_to_string` and `load_from_string` on that instead." - ) - out_dict: Dict[str, Any] = { - "index_struct_id": self.index_struct.get_doc_id(), - "docstore": self.docstore.serialize_to_dict(), - "sql_context_container": self.sql_context_container.to_dict(), - } - return json.dumps(out_dict, **save_kwargs) diff --git a/spaces/jokogadingan/joko-gadingan-image-description-project/README.md b/spaces/jokogadingan/joko-gadingan-image-description-project/README.md deleted file mode 100644 index 62c73c1635ea6427184f74bb9a1a0e5cf77454fd..0000000000000000000000000000000000000000 --- a/spaces/jokogadingan/joko-gadingan-image-description-project/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Blip Api -emoji: 🏃 -colorFrom: pink -colorTo: purple -sdk: gradio -sdk_version: 3.50.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/josStorer/ChatGLM-6B-Int4-API-OpenAI-Compatible/models/models--silver--chatglm-6b-int4-slim/snapshots/02e096b3805c579caf5741a6d8eddd5ba7a74e0d/quantization.py b/spaces/josStorer/ChatGLM-6B-Int4-API-OpenAI-Compatible/models/models--silver--chatglm-6b-int4-slim/snapshots/02e096b3805c579caf5741a6d8eddd5ba7a74e0d/quantization.py deleted file mode 100644 index 69c502b4eb71836464037cfd1703762c5be0cfa4..0000000000000000000000000000000000000000 --- a/spaces/josStorer/ChatGLM-6B-Int4-API-OpenAI-Compatible/models/models--silver--chatglm-6b-int4-slim/snapshots/02e096b3805c579caf5741a6d8eddd5ba7a74e0d/quantization.py +++ /dev/null @@ -1,469 +0,0 @@ -from torch.nn import Linear, Embedding -from torch.nn.parameter import Parameter -import torch.nn.functional as F - -import os -import bz2 -import torch -import base64 -import ctypes - -from typing import List -from functools import partial -from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up - - -class W8A16Linear(torch.autograd.Function): - @staticmethod - def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width): - ctx.inp_shape = inp.size() - ctx.weight_shape = quant_w.size() - ctx.weight_bit_width = weight_bit_width - out_features = quant_w.size(0) - inp = inp.contiguous().view(-1, inp.size(-1)) - weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width) - output = inp.mm(weight.t()) - ctx.save_for_backward(inp, quant_w, scale_w) - return output.view(*(ctx.inp_shape[:-1] + (out_features,))) - - @staticmethod - def backward(ctx, grad_output: torch.Tensor): - inp, quant_w, scale_w = ctx.saved_tensors - weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width) - grad_output = grad_output.contiguous().view(-1, weight.size(0)) - grad_input = grad_output.mm(weight) - grad_weight = grad_output.t().mm(inp) - return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None - - -class W8A16LinearCPU(torch.autograd.Function): - @staticmethod - def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width, quantization_cache=None): - ctx.inp_shape = inp.size() - ctx.weight_shape = quant_w.size() - ctx.weight_bit_width = weight_bit_width - out_features = quant_w.size(0) - inp = inp.contiguous().view(-1, inp.size(-1)) - weight = extract_weight_to_float(quant_w, scale_w, weight_bit_width, quantization_cache=quantization_cache) - output = inp.mm(weight.t()) - ctx.save_for_backward(inp, quant_w, scale_w) - return output.view(*(ctx.inp_shape[:-1] + (out_features,))) - - @staticmethod - def backward(ctx, grad_output: torch.Tensor): - inp, quant_w, scale_w = ctx.saved_tensors - weight = extract_weight_to_float(quant_w, scale_w, ctx.weight_bit_width) - grad_output = grad_output.contiguous().view(-1, weight.size(0)) - grad_input = grad_output.mm(weight) - grad_weight = grad_output.t().mm(inp) - return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None - - -class Kernel: - def __init__(self, code: bytes, function_names: List[str]): - self.code = code - self._function_names = function_names - self._cmodule = LazyKernelCModule(self.code) - - for name in self._function_names: - setattr(self, name, KernelFunction(self._cmodule, name)) - -default_cpu_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels.c") -default_cpu_kernel_code = "QlpoOTFBWSZTWXLbSoQAAgzbgERwQXxmTwAAr/ff3kABt0Q2oRVT0hpo9RtEAAAAyBEiSQ9EGjQGQAAAwANGhowjJoNGmgMEUplMTNSMJ5TQaDJpsoMyRMj8P4mZzFSVVwqSXG8GG7MlVwiToYEQwVD7noBxMhNfkeZYtYFtbgOBUSIGtIQjhNHCEnPJsadhb3yBmRIOD3TeAtNLSaU5GgvKUBWSNuuOIHmVt0YhW6rsmDMDUjeUJGJ64R1Jm5lrh0Aa0tKjhFwPdWcGogxLDSXPWQUWTM8Sd3Qz1HMYNxx3HMeiNqNo4jeRDEfZ3gUSHIcU/heomq0vEzL1Msz5KKGxH8FrNOYw3KaxdqaEmNHYMxJFgQbR0DyRknL2L4kwUSxKRdhjRpEtUqilVfggFL1klaMS3PPRDfNqbBOPWO7m4JTVGhS9QTBDDJaEbLbrUQNB+IpJSKQbG5SZZ5gkwJEhJ3aYKJipZ/i7kinChIOW2lQg" -default_cpu_parallel_kernel_code_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quantization_kernels_parallel.c") -default_cpu_parallel_kernel_code = "QlpoOTFBWSZTWZzWK2UAALXbgERwSX1mTwAAr/ff3kACNyXSbZYwBpoaNGIyAaADQwRRFT/UKDINANqAD1NABFQlPUzaaJHppGRmoAG01ARKKaaMp4gmgaNAaDQDIKVKfZ/g6v1Kem5ZsWZmZtSXS5ZwRAzKmjr1E1lKMEoQNCPkEYPACgcR5I9w/0k6JrJYHqFuHnChcD7N+DHeOQ0ajF83Tc40jgmQbOB5wt3TEHyTObDBLoxrJGBuJmNbxYZwAoKTjbIcI7GsbuVRERAR8wqwhXQjQOxiHQlgSnHjQjddXERojNmQYJJVoM2xxawMeI9asi6E1rfd7GO8S0S5vacCNGry4F1nyZbcTvSBXEMipuPfM7i0Y8kjirpbxb05jpIQjCGE8DYBNCAZyHz9EoOpDRST/I1aFCNpcjoXgyc3NjVsUvYIaYq7xopYJqcxg2g4qXofm7AaGNTzJSNguOQw4utKcEl0F1UOgI+T1hk5LusbGZ9udC1CiBeGwwFxR/QdbZDndehRPxyGt3Me1DBW45MXIY24ZD30aFNuSEUdu5LWx1sSJWLGgsmqUIFTgWhU0gfxXpzhghr2AYpV3hE06mGk1I2JyuZiFgkiz/i7kinChITmsVso" - - -class CPUKernel: - def __init__(self, kernel_file="", source_code=default_cpu_kernel_code_path, compile_parallel_kernel=None, parallel_num=None): - self.load =False - self.int8WeightExtractionFloat = None - self.int4WeightExtractionFloat = None - self.int4WeightCompression = None - self.SetNumThreads = None - - try: - if not os.path.exists(default_cpu_kernel_code_path): - with open(default_cpu_kernel_code_path, "w", encoding="utf-8") as file: - code = default_cpu_kernel_code - cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode() - file.write(cpu_quantization_code) - - if not os.path.exists(default_cpu_parallel_kernel_code_path): - with open(default_cpu_parallel_kernel_code_path, "w", encoding="utf-8") as file: - code = default_cpu_parallel_kernel_code - cpu_quantization_code = bz2.decompress(base64.b64decode(code)).decode() - file.write(cpu_quantization_code) - - except Exception as ex: - print("Error when generating default cpu kernel code(can be ignored when using custom kernels).") - - if compile_parallel_kernel is None: - compile_parallel_kernel = bool(int(os.cpu_count()) >= 4) - - if compile_parallel_kernel and source_code == default_cpu_kernel_code_path: - source_code = default_cpu_parallel_kernel_code_path - - if (not kernel_file) or (not os.path.exists(kernel_file)): - print("No compiled kernel found.") - try: - if os.path.exists(source_code): - print("Compiling kernels :", source_code) - kernel_file = source_code[:-2] + ".so" - if compile_parallel_kernel: - compile_command = "gcc -O3 -pthread -fopenmp -std=c99 {} -shared -o {}".format(source_code, kernel_file) - print("Compiling", compile_command) - exit_state = os.system(compile_command) - if exit_state: - print("Compile failed, using default cpu kernel code.") - compile_parallel_kernel = False - source_code = default_cpu_kernel_code_path - kernel_file = source_code[:-2] + ".so" - compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file) - print("Compiling", compile_command) - else: - compile_command = "gcc -O3 -fPIC -std=c99 {} -shared -o {}".format(source_code, kernel_file) - print("Compiling", compile_command) - exit_state = os.system(compile_command) - - print("Kernels compiled :", kernel_file) - else: - print("Kernel source code not found.") - return - except: - print("Failed to build kernel.") - return - if kernel_file: - kernels = ctypes.cdll.LoadLibrary(kernel_file) - self.int8WeightExtractionFloat = kernels.extract_int8_weight_to_float - self.int4WeightExtractionFloat = kernels.extract_int4_weight_to_float - self.int4WeightCompression = kernels.compress_int4_weight - if compile_parallel_kernel: - try: - self.SetNumThreads = kernels.set_num_threads - except: - print("No set_num_threads() found in kernel.") - self.SetNumThreads = lambda x: x - self.load = True - print("Load kernel :", kernel_file) - else: - print("Failed to load kernel.") - - if compile_parallel_kernel: - if parallel_num is None: - parallel_num = max(os.cpu_count() // 2, 1) - print("Setting CPU quantization kernel threads to", parallel_num) - if parallel_num < 4: - print("Parallel kernel is not recommended when parallel num < 4.") - self.SetNumThreads(parallel_num) - - self.parallel_num = parallel_num - - -cpu_kernels = None - -quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rxjwztHlnire3Nzc3N1wuBwOBwXBvZfoHpD7rFmR99V5vj3aXza3xdBbXMalubTg/jIv5dfAi54Pdc75j4z412n3Npj3Ld/ENm7a3b/Cod6h/ret1/5vn/C+l+gdslMvgPSLJ8d8q+U66fevYn/tW1chleEtNTGlcHCbLRlq0tHzF5tsbbZZfHjjLgZu42XCuC3NrdjTasZGNzgxPIrGqp7r3p7L2p5XjnpPSmTd5XtzqnB6U87zzg1Ol0zd0zsLszxR6lkxp35u6/teL0L0W922cR7Lu1lpL9CsHirzuM2T+BgsyViT6LHcm0/Vr6U/7LGGyJeqTEjt0PHWhF5mCT7R9mtlDwriYv0Tyr/OxYt6qp5r0mPVT0608TqnqMZaarU2nFwrTzzlrs1ed7z1ux60wyr4ydCaTi3enW8x68x0zU7tXSlcmPSW1mGpWJMg4zmPC2lK96tp0OE80y4MfEvnZj8zGluR6b22ki1Ou9V2nCd9xovcPvcYMZYy0lvN60ScZ45vN6yeCeeXFb1lVjnnCar5fwXwE2bzJ4HI1XVPXfXZMm44GUsMpYsmLB65TuVdm0cl0b+i/wGNN66XjeV7zuPpHcnK/juhhjdfId5jMdE5nN0dGmmm2zZs2cexD5n9p/dY352XsvXHaZNWWsmmS1atjR452nYudzvqv2HMRyvNNnlMcDl3R2+yx2uVrBubTW9icHDVtbNXlZm7jma1rM4VurZZd2y6nUau7ZXZ7bVU+mnoOVxZGMrVmvX60605JwmzGZhhhjTWtaaaMaaGTGmNMZasY0iX8VMUl8eepaIrzGSpemWOQyZORk2bNpjUybMmxqYmknCGCFynutfksaZpjTNMaaatM0xsxcGR0sociNqxNSmhhR1ZJPbsn8qyF0t2qH6iYBclclalbtTTcHTDsPaX6rlnElph2Jyumumtynv2Kk8GI7rsvXbIcJgHJOSaSXnnGaI3m87RtVXJOZ/YtgdTE6Wpha6ZlE8ayXkef1fh602r2WwvfMXtMdLlkfnLFdYYwYso+bWqm7yJqHXZGw2nrS5ZanSYnWlxBxMF1V940K2wdrI7R6OYf7DGGamMmTSbRhlS45xmVOumF1EyPCmHrrN8wwZOOrdNtLeMtzFzDlWnfTBxMk2NaXIZHBYxYLD4w8yju0ao65Vz1OIXoS9dLanwCe1PWrYuWMqf1if1z2k2yYfKJ741PDgno1ZQ8DRqvUny3mNoWTzGO6m1DkrJI8JiR5cSd+vZdGOO8nrMoc5+NDUFsMSXaZJeNlMmGLtJsovOsUp7I9S5VojKxF6bTVEelXqlfJobQr3LozSh2Jk7VcrVMfhXqszGWMzNqGhqZY0OadxkyyMssKugZR0KNFXBHlqwmJgTE/BNVMk6ItJXZMR0H47GpXv/DMOvNkmVuaV1PRfEdxuqc7Hcd+ZV/zTLaRxWk0nl9CdCeM6mn5rstHIBcpiuwmUZXeq81DacHI2rmrZ5SuE5mOZd6LQrZg9mx32TprA8BMo5jKN6yLTCi3WzQaZSuhzTtM1fUTGVpG8Tw+KXI0tjEpiWxtLYynOlktSbVlaI5kxP8TDH8kx50xoxi5KcA4pcja8KWLRlO/Ks6q06ergnvm1ca3Tq8Uw7LTUsmWyctXPWmpitl/uvGcWTGXGuAXDfhqazGmjkxcJW5hMMMMpYsXl2TZYtVOddG3XCarUt6Ptq9CZXSNzyuRzqRZOjsxdBbFVz6OA5HI43r1jityVlVpVkxmOsyaYWE1NTGq1sOVh36mHMcxtSvcy70edG0ZGR3I1Go1GRlV7mWWo1G0ZGRqlvH40l7o4m5xMWLLLYyNjnqc8556mdPqLJ31n/1nWOncxzG1tizrHs/Z+d2vP/B/l8wdJ6rHUn2nbbDq4p6htFtYzMMMTaZis1K5GKzGNmxhmUx2DDlZ/qNnIx41xnaMfCZWYaZWtNLTNW8ND4Fw1MyZOCdM428suKG1ehW8TesOydg7J+YYcD4cYR+8dFK6M4E3HM9ZfRNNL+Sn6rsl4DsrDl2HpPCnfxjGXtbZtYys1ttlyJ4T+BvexjGWRjMszK4Jpc77D3GyuVD7q0+G8m9G+2+rGm7cOR2y7FdtY2XUYx/oNlfRYxhMYyYZkyyg55enna9Kt/FFi6GMMwYwdwxWgxGMLKYmUyGExTKMZkMFhkymKuh0NOBNnBu+23LdwDoZYYzGGMxtORaTU1pjTGWTTGGtMrNWUsyyTTLLG1qy2ZjbK2DBllWqxMtBMaYZQmcE7zvvRcTkclUwdkxTaSdyySt/7fpL+T1v516Ji97fwr5JbLu305zMn5+GMTTZ9F+y7ExwmGVfG44yxn3dLv6l5i+Wth1jCrDq21nW9LqvvDzz3Vf3LLH/O/32TJ/erx3bXftO4eF+G956D952K/An4NfvOpjFjExjevP/UmE0fIoZXx6/w6lX/no3D0bLt+ixjieBM6ksRd0yB4Lt2SwYNE+gd1detlZWUnpiZfGfFaK+4PyCa/v18V8X75pe9fLXzp7l3VjF76vWZmHwGz1IZNWT7b8yddJ4q5kyrVdfru6atWc7bVYztL9Jf4GXvT+Y8m9/YsXP6H018a8D4XVOqvfzqeR+6yZOD8dPv0+U7/q5Pl+2dNb0MjzGVH5p6MNQ7cOWvw62U9aHE8DprDek+McLyvDz+te+9Zhq5+YTruufMcWMabqysTmZVWjKPfnK0wyVcrsuhjZRdLkHNvD72b9abriOSGIxiLixMOoalNPXzy+wT/tf+U6HHONfsz+xe8ufHBdQWWGWLA9if0rsnmrxK5LvRZQeWsTCsrmOYy8VteVfuRfcVTtDLItLIsMYxZLdU/DbtSemxF6Z6Zo5WBXE4tFdCyVMMXMTEMZXVlS6Xec2T4e0tHsRcEuWshcJ2YsNF5rUx1E8ifCq6Z+ZP7qdCeu/aTwFd53l16/o0NOw6O3dLavP4Hbi4RdmuDk6DoYaninC0+o4uZjbJ7Rxeu0/FbuFg+q7DVS6fQe0rZ6NDGUNNU6DEqOaLTicKnYZMnBWruljQxoaS3dZhocDge0bSTyOvdAbG5hxe2xji7E/L55xX13wWNDi6HCekcFxfCPGxY0MXC+s7afWaMdDyjyr+o8Rudm/NabOZvdl274zH4f5XK9z6On1Pe/K5TdPAslg77BjuO6Y3eO7GqvOPG/stknp1leyvLL0Z7bl9I4noMvLkzytLhWYzrOZzLXCORe028rORzOg4N/L0HlMOQ3Pgmnbb6KczlabORpu980q37TBqRu0/p3PO6234Bl03Ynuz+9W7gnsEcmvYaYY3aMYY0wx3pYd+ujsXauWdaY5Xkbtl23fPzFHiDB/QMo0yFjBllYxTQYYyxkrwn7JufwJ/PfgJ+C83X69ni6zvXcnyXabv0ncbLwsceS+RNlyN2mnneJtX0ngYO0+e+0+UnA+Wch3ji8hj5an4h+i6XBySU4n+R0roVcbw5yvHrmr4Yw8Y7x6c+9POPYHI5HI5HI5HI5HGXGww4nE4nrVyOR8XeqPEO7PLOiukYa3Novk5hV4cdtYZLI93e+uxff2jRo0aNGjRo0aNG1bVtW1dy3m83m8+tQ5ZzHw3nObwOu8La9Rc1dtkdS8A3eTk823tnktXWlxN6Oixe06zrN70Isd9jiOgZFq9yfkPqP/SLhN2Myl8jDM43bl1nbcb4cO57jlh8Jow6pzXZdL4dyODTuuhu77FyO27DdwdRxmvO+O+3N2+BdqyTwLHVczDVY4UPE4O66/ZO2cx1LFzVdSXtF7G4HMbrauOHRw6c8FdZ5m9fHZHYZXfTlZquyynSyTTKke6vcffSD9pzPA/G7n7jxPmuhc1DHMynPMrGL6AdewYmwu5ko+UUyTwrMv27rPH1v1nGqd87+p6N6LU8k3NEng53xXyHS97+44OSg/sy/hn+Se6yfYNjW0/uTgP+PvWYzLMmjhcLB/gGpri6H83/84eUXWT6T9Hsv7785z/7z4icpW+zfXypuR7rx/gMdZb1/wC678pcs8/2a3mDitGHxl9mfPlll5MafWWqxk/eYuTDgcNMzDGWLWvsuglNxs53GtN6uWpktlW1tZZYcuinMMWmnNnJydze3b2Y1McBxrBkXw799izLMZZYyy0TkbsGM4p03S2uVu5s/XXUdSdec6smVxZYYGpVmT8A+8ajuEyV5FatkvVru2x6uxGXXbH4A+jvgP4GMYy3iPLXzq/6z65+E005ey+cwMZD3fZcqc6xpjTFjQ0P3U+e++cPYmTIwj0nrK5NPTfl3WvpfLtXDcb2HQMudYOxFXQBor4L4T6vrOauFctYXJQ++NUWmJe5bmx1jDiZS1dTqWxo4GR8jm3fttpmPHppk9PEyv4/y8/sO07XacOmcqc0x2Vi9BvNJvN5oW8x4mOsydpidRxMYJPx06m1bqPzq9KtK8sxXNXFodD/+MYYaJTLwOhc9brCsV18oOR1i4tXChyTkq4lf4y1Ke+9axjDHqs1mfBbMXuP4Hzi+X7t8vzv7bHerrUPgPCxhjre4fXdfLNtNM+Jd+Zdh8xd8wP87uNPoPgv4W7/5P2BuxfsMabNnMnza+54Pdi5U671GPZY8CehX8Voeoo7FHpkeEc6715FwHZrIrUrHaviPUbPZHND+IhczrP6FcYvhOZ0Di/ETt0OI+YwNWR9r7tpf6WDeZKZDB1+z2IthOl1mPyb5FluvEx9h9d0NnM0Y1XPFkWIsk1WotJ0PBMmkvjvQTd0e71tfeV+8r8lQ/tpzpsmxJ+InrI/dj2UajUajVTUajatRqNRtGo1Go1Go4wjeMpZFMVV9CHbofPraLsJ3JpWV2XOoanCuFky4y3PPNxucK2uKC1Lbdb1eo+m5XomN6HfeZsabHLHRX/K+offtNGGmHWctcVcG44MdSqsOLY9VzX+Zxfxn2HPdWTpzWvkrtJ8M5zorrKcquRytJ5N5DZmcaW02l76nWO+BqPXm1A2Ry/0q71dH/mqrqeFjkYxjEXtsX8qubTk67rGycyqsdm4tZx5D6D5hhi0waaWmiaMP81Yjii5qxPlPuU/GfTL1Y5E6Jyfiq63qTa39A4J0sOGDgO9WF9bOXl0XfPRbsY2bPNKPy1YrFYrFYmRhhlTIyMjJWJYZHXuCXI8OoXsvfljGLFicNifpp2XunoPiG1wtx3p1Tah+/DD66OnVtVXP9rKbVxOnL0tR/rHtqB5UDErUVcl11D4qqvjpOcxX7armUNJB3LpW6bxVvD08e8h3odKKvyCFZBdSh2FVcST9xV3n3T8t1j7Kr9qgrqXg+13Pt5U7JCvFXVIV1YG5lRhkVYZJYYDDD4KOIMoHCp26WS8GB7uBh2zIdgq/PKyInjV2STShuoapUdCpX1yTwqq/z1VvET7Kh5nVPkO8YyxjLt2MaaMmWTLQvx3qnzltnXW0p2jxgbEtSny/Osv8Y9pLMXYoHVPAhkVdWVeODhR6q9/Sxe2liwwZWMVvFXfRkeIDxAePUPIrdJ4ey6yquzH+PD/bUOWAu05qVHtFd8rrKHSoeNIOUqrYr3FXyToqfYJgwmJdKpXXOwYYegNNGMzfZPp/t3t/DVs4zjNTN61rRqaWaa4NYbRjTa0tWwy2Y2tGN8ZO8ofNKq4j9SL7I+cSm4/6ovLV5HNXLI0jJidwrtk6ynCaP6Z++GjRlWS3tLeW129Mi9evxU9mtz6s5J3Z7M2ngTgnKvmpomxpaLCzPfmx0JWE+m3NLDDGOX47RctdYYNK5jakdqLkRlI39n590T5zctGSwwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ" - -kernels = Kernel( - bz2.decompress(base64.b64decode(quantization_code)), - [ - "int4WeightCompression", - "int4WeightExtractionFloat", - "int4WeightExtractionHalf", - "int8WeightExtractionFloat", - "int8WeightExtractionHalf", - ], -) - - -def compress_int4_weight(weight: torch.Tensor): # (n, m) - """compress weight on cpu or cuda to int4""" - if weight.device == torch.device("cpu"): - assert isinstance(cpu_kernels, CPUKernel) - n, m = weight.size(0), weight.size(1) - assert m % 2 == 0 - m = m // 2 - out = torch.empty(n, m, dtype=torch.int8, device="cpu") - cpu_kernels.int4WeightCompression( - ctypes.c_void_p(weight.data_ptr()), - ctypes.c_void_p(out.data_ptr()), - ctypes.c_int32(n), - ctypes.c_int32(m) - ) - return out - else: - with torch.cuda.device(weight.device): - n, m = weight.size(0), weight.size(1) - assert m % 2 == 0 - m = m // 2 - out = torch.empty(n, m, dtype=torch.int8, device="cuda") - stream = torch.cuda.current_stream() - - gridDim = (n, 1, 1) - blockDim = (min(round_up(m, 32), 1024), 1, 1) - - kernels.int4WeightCompression( - gridDim, - blockDim, - 0, - stream, - [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)], - ) - return out - - -def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int): - if source_bit_width == 8: - func = kernels.int8WeightExtractionHalf - elif source_bit_width == 4: - func = kernels.int4WeightExtractionHalf - else: - assert False, "Unsupported bit-width" - - with torch.cuda.device(weight.device): - n, m = weight.size(0), weight.size(1) - out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda") - stream = torch.cuda.current_stream() - - gridDim = (n, 1, 1) - blockDim = (min(round_up(m, 32), 1024), 1, 1) - - func( - gridDim, - blockDim, - 0, - stream, - [ - ctypes.c_void_p(weight.data_ptr()), - ctypes.c_void_p(scale_list.data_ptr()), - ctypes.c_void_p(out.data_ptr()), - ctypes.c_int32(n), - ctypes.c_int32(m), - ], - ) - return out - - -def extract_weight_to_float(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int, quantization_cache=None): - """extract weight on cpu to float32""" - if source_bit_width == 8: - func = cpu_kernels.int8WeightExtractionFloat - elif source_bit_width == 4: - func = cpu_kernels.int4WeightExtractionFloat - else: - assert False, "Unsupported bit-width" - - n, m = weight.size(0), weight.size(1) - - if quantization_cache is not None: - out = quantization_cache - func( - ctypes.c_void_p(weight.data_ptr()), - ctypes.c_void_p(scale_list.data_ptr()), - ctypes.c_void_p(out.data_ptr()), - ctypes.c_int32(n), - ctypes.c_int32(m) - ) - return out.tensor - else: - out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.float, device="cpu") - func( - ctypes.c_void_p(weight.data_ptr()), - ctypes.c_void_p(scale_list.data_ptr()), - ctypes.c_void_p(out.data_ptr()), - ctypes.c_int32(n), - ctypes.c_int32(m) - ) - return out - - -class CacheTensor(): - def __init__(self, *args, **kwargs): - self.tensor = torch.empty(*args, **kwargs) - - def to(self, *args, **kwargs): - self.tensor = self.tensor.to(*args, **kwargs) - - def data_ptr(self): - return self.tensor.data_ptr() - - -class QuantizedLinear(Linear): - def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, quantized_weight=None, quantized_weight_scale=None, quantization_cache=None, empty_init=False, *args, **kwargs): - super(QuantizedLinear, self).__init__(*args, **kwargs) - self.weight_bit_width = weight_bit_width - self.quantization_cache = quantization_cache - - if (quantized_weight is not None) and (quantized_weight_scale is not None): - del self.weight - self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False) - self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False) - else: - shape = self.weight.shape - del self.weight - - if weight_tensor is None or empty_init: - self.weight = torch.empty( - shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"] - ) - self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"]) - else: - self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).to(kwargs["dtype"]) - self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8) - if weight_bit_width == 4: - self.weight = compress_int4_weight(self.weight) - - self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False) - self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False) - - if bias_tensor is not None: - self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False) - else: - self.bias = None - - def reset_parameters(self): - """To accelerate initialization""" - pass - - def forward(self, input): - if self.weight.device == torch.device("cpu"): - output = W8A16LinearCPU.apply(input, self.weight, self.weight_scale, self.weight_bit_width, self.quantization_cache) - else: - output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width) - if self.bias is not None: - output = output + self.bias - return output - - def _apply(self, fn): - self_obj = super()._apply(fn) - if self.quantization_cache is not None: - self.quantization_cache.to(self_obj.weight.device) - self.quantization_cache.to(self_obj.weight_scale.dtype) - return self_obj - - -class QuantizedEmbedding(Embedding): # TODO: backward, check empty_init - def __init__(self, weight_bit_width: int, weight_tensor=None, quantized_weight=None, quantized_weight_scale=None, empty_init=False, *args, **kwargs): - super(QuantizedEmbedding, self).__init__(*args, **kwargs) - self.weight_bit_width = weight_bit_width - - if (quantized_weight is not None) and (quantized_weight_scale is not None): - del self.weight - self.weight = Parameter(quantized_weight.to(kwargs["device"]), requires_grad=False) - self.weight_scale = Parameter(quantized_weight_scale.to(kwargs["device"]), requires_grad=False) - else: - shape = self.weight.shape - del self.weight - - if weight_tensor is None or empty_init: - self.weight = torch.empty( - shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"] - ) - self.weight_scale = torch.empty(shape[0], dtype=kwargs["dtype"], device=kwargs["device"]) - else: - self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half() - self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8) - if weight_bit_width == 4: - self.weight = compress_int4_weight(self.weight) - - self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False) - self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False) - - def forward(self, input): - if self.weight.device == torch.device("cpu"): - original_weight = extract_weight_to_float(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width) - else: - original_weight = extract_weight_to_half(weight=self.weight, scale_list=self.weight_scale, source_bit_width=self.weight_bit_width) - output = F.embedding( - input, original_weight, self.padding_idx, self.max_norm, - self.norm_type, self.scale_grad_by_freq, self.sparse - ) - return output - - -def load_cpu_kernel(**kwargs): - global cpu_kernels - cpu_kernels = CPUKernel(**kwargs) - assert cpu_kernels.load - - -def quantize(model, weight_bit_width, use_quantization_cache=False, empty_init=False, **kwargs): - """Replace fp16 linear with quantized linear""" - - query_key_value_quantization_cache = None - dense_quantization_cache = None - dense_h_to_4h_quantization_cache = None - dense_4h_to_h_quantization_cache = None - - try: - load_cpu_kernel(**kwargs) - except: - print("Cannot load cpu kernel, don't use quantized model on cpu.") - - current_device = model.device - - if model.device == torch.device("cpu"): - dtype=torch.float32 - else: - dtype = torch.half - - QuantizedLinearWithPara = partial( - QuantizedLinear, - weight_bit_width=weight_bit_width, - bias=True, - dtype=dtype, - empty_init=empty_init - ) - - if use_quantization_cache: - print("Using quantization cache") - layer = model.layers[0] - weight = layer.attention.query_key_value.weight - n, m = weight.size(0), weight.size(1) - query_key_value_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False) - weight = layer.attention.dense.weight - n, m = weight.size(0), weight.size(1) - dense_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False) - weight = layer.mlp.dense_h_to_4h.weight - n, m = weight.size(0), weight.size(1) - dense_h_to_4h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False) - weight = layer.mlp.dense_4h_to_h.weight - n, m = weight.size(0), weight.size(1) - dense_4h_to_h_quantization_cache = CacheTensor(n, m, dtype=dtype, device=current_device, requires_grad=False) - - print("Applying quantization to glm layers") - - for layer in model.layers: - layer.attention.query_key_value = QuantizedLinearWithPara( - weight_tensor=layer.attention.query_key_value.weight.to(current_device), - bias_tensor=layer.attention.query_key_value.bias, - in_features=layer.attention.query_key_value.in_features, - out_features=layer.attention.query_key_value.out_features, - device=layer.attention.query_key_value.weight.device, - quantization_cache=query_key_value_quantization_cache - ) - layer.attention.dense = QuantizedLinearWithPara( - weight_tensor=layer.attention.dense.weight.to(current_device), - bias_tensor=layer.attention.dense.bias, - in_features=layer.attention.dense.in_features, - out_features=layer.attention.dense.out_features, - device=layer.attention.dense.weight.device, - quantization_cache=dense_quantization_cache - ) - layer.mlp.dense_h_to_4h = QuantizedLinearWithPara( - weight_tensor=layer.mlp.dense_h_to_4h.weight.to(current_device), - bias_tensor=layer.mlp.dense_h_to_4h.bias, - in_features=layer.mlp.dense_h_to_4h.in_features, - out_features=layer.mlp.dense_h_to_4h.out_features, - device=layer.mlp.dense_h_to_4h.weight.device, - quantization_cache=dense_h_to_4h_quantization_cache - ) - layer.mlp.dense_4h_to_h = QuantizedLinearWithPara( - weight_tensor=layer.mlp.dense_4h_to_h.weight.to(current_device), - bias_tensor=layer.mlp.dense_4h_to_h.bias, - in_features=layer.mlp.dense_4h_to_h.in_features, - out_features=layer.mlp.dense_4h_to_h.out_features, - device=layer.mlp.dense_4h_to_h.weight.device, - quantization_cache=dense_4h_to_h_quantization_cache - ) - return model diff --git a/spaces/juancopi81/multilingual-stable-diffusion/README.md b/spaces/juancopi81/multilingual-stable-diffusion/README.md deleted file mode 100644 index 9310fe34dadcdc5eac6c72e403ccc6478ac7dd66..0000000000000000000000000000000000000000 --- a/spaces/juancopi81/multilingual-stable-diffusion/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Multilingual Stable Diffusion -emoji: 💥 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.9 -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/jvictoria/LogicChecker/README.md b/spaces/jvictoria/LogicChecker/README.md deleted file mode 100644 index ad55575bff531d59c8b60abf71736151b8936225..0000000000000000000000000000000000000000 --- a/spaces/jvictoria/LogicChecker/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: LogicChecker -emoji: ⚡ -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.29.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/kamezawash/rembg/README.md b/spaces/kamezawash/rembg/README.md deleted file mode 100644 index fd48412545611863c79328462f96b96a9adb476c..0000000000000000000000000000000000000000 --- a/spaces/kamezawash/rembg/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Rembg -emoji: 👁 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.1.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/kanden/vits-uma-genshin-honkai/mel_processing.py b/spaces/kanden/vits-uma-genshin-honkai/mel_processing.py deleted file mode 100644 index 3e252e76320522a8a4195a60665168f22769aec2..0000000000000000000000000000000000000000 --- a/spaces/kanden/vits-uma-genshin-honkai/mel_processing.py +++ /dev/null @@ -1,101 +0,0 @@ -import torch -import torch.utils.data -from librosa.filters import mel as librosa_mel_fn - -MAX_WAV_VALUE = 32768.0 - - -def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): - """ - PARAMS - ------ - C: compression factor - """ - return torch.log(torch.clamp(x, min=clip_val) * C) - - -def dynamic_range_decompression_torch(x, C=1): - """ - PARAMS - ------ - C: compression factor used to compress - """ - return torch.exp(x) / C - - -def spectral_normalize_torch(magnitudes): - output = dynamic_range_compression_torch(magnitudes) - return output - - -def spectral_de_normalize_torch(magnitudes): - output = dynamic_range_decompression_torch(magnitudes) - return output - - -mel_basis = {} -hann_window = {} - - -def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False): - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - global hann_window - dtype_device = str(y.dtype) + '_' + str(y.device) - wnsize_dtype_device = str(win_size) + '_' + dtype_device - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], - center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - return spec - - -def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax): - global mel_basis - dtype_device = str(spec.dtype) + '_' + str(spec.device) - fmax_dtype_device = str(fmax) + '_' + dtype_device - if fmax_dtype_device not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device) - spec = torch.matmul(mel_basis[fmax_dtype_device], spec) - spec = spectral_normalize_torch(spec) - return spec - - -def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False): - if torch.min(y) < -1.: - print('min value is ', torch.min(y)) - if torch.max(y) > 1.: - print('max value is ', torch.max(y)) - - global mel_basis, hann_window - dtype_device = str(y.dtype) + '_' + str(y.device) - fmax_dtype_device = str(fmax) + '_' + dtype_device - wnsize_dtype_device = str(win_size) + '_' + dtype_device - if fmax_dtype_device not in mel_basis: - mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax) - mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device) - if wnsize_dtype_device not in hann_window: - hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device) - - y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect') - y = y.squeeze(1) - - spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device], - center=center, pad_mode='reflect', normalized=False, onesided=True) - - spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6) - - spec = torch.matmul(mel_basis[fmax_dtype_device], spec) - spec = spectral_normalize_torch(spec) - - return spec diff --git a/spaces/kepl/add/index.html b/spaces/kepl/add/index.html deleted file mode 100644 index 37e9ca0106f4f407dd7b36b2fe1ab96be0d01696..0000000000000000000000000000000000000000 --- a/spaces/kepl/add/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - KeplBot - - - - -

    KeplBot

    -

    Redirecting . . .

    - - diff --git a/spaces/keras-io/semantic-image-clustering/README.md b/spaces/keras-io/semantic-image-clustering/README.md deleted file mode 100644 index 57388615bd6fb64fdb72dd16711376fec34776f6..0000000000000000000000000000000000000000 --- a/spaces/keras-io/semantic-image-clustering/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Semantic Image Clustering -emoji: 🖼️ -colorFrom: red -colorTo: yellow -sdk: gradio -sdk_version: 3.0.12 -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/kevin-dw/runwayml-stable-diffusion-v1-5/app.py b/spaces/kevin-dw/runwayml-stable-diffusion-v1-5/app.py deleted file mode 100644 index a82df332731f067826d3e1ef79fabceffb74d07e..0000000000000000000000000000000000000000 --- a/spaces/kevin-dw/runwayml-stable-diffusion-v1-5/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/runwayml/stable-diffusion-v1-5").launch() \ No newline at end of file diff --git a/spaces/kevinwang676/M4Singer/modules/parallel_wavegan/layers/residual_stack.py b/spaces/kevinwang676/M4Singer/modules/parallel_wavegan/layers/residual_stack.py deleted file mode 100644 index 6e07c8803ad348dd923f6b7c0f7aff14aab9cf78..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/M4Singer/modules/parallel_wavegan/layers/residual_stack.py +++ /dev/null @@ -1,75 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Tomoki Hayashi -# MIT License (https://opensource.org/licenses/MIT) - -"""Residual stack module in MelGAN.""" - -import torch - -from . import CausalConv1d - - -class ResidualStack(torch.nn.Module): - """Residual stack module introduced in MelGAN.""" - - def __init__(self, - kernel_size=3, - channels=32, - dilation=1, - bias=True, - nonlinear_activation="LeakyReLU", - nonlinear_activation_params={"negative_slope": 0.2}, - pad="ReflectionPad1d", - pad_params={}, - use_causal_conv=False, - ): - """Initialize ResidualStack module. - - Args: - kernel_size (int): Kernel size of dilation convolution layer. - channels (int): Number of channels of convolution layers. - dilation (int): Dilation factor. - bias (bool): Whether to add bias parameter in convolution layers. - nonlinear_activation (str): Activation function module name. - nonlinear_activation_params (dict): Hyperparameters for activation function. - pad (str): Padding function module name before dilated convolution layer. - pad_params (dict): Hyperparameters for padding function. - use_causal_conv (bool): Whether to use causal convolution. - - """ - super(ResidualStack, self).__init__() - - # defile residual stack part - if not use_causal_conv: - assert (kernel_size - 1) % 2 == 0, "Not support even number kernel size." - self.stack = torch.nn.Sequential( - getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params), - getattr(torch.nn, pad)((kernel_size - 1) // 2 * dilation, **pad_params), - torch.nn.Conv1d(channels, channels, kernel_size, dilation=dilation, bias=bias), - getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params), - torch.nn.Conv1d(channels, channels, 1, bias=bias), - ) - else: - self.stack = torch.nn.Sequential( - getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params), - CausalConv1d(channels, channels, kernel_size, dilation=dilation, - bias=bias, pad=pad, pad_params=pad_params), - getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params), - torch.nn.Conv1d(channels, channels, 1, bias=bias), - ) - - # defile extra layer for skip connection - self.skip_layer = torch.nn.Conv1d(channels, channels, 1, bias=bias) - - def forward(self, c): - """Calculate forward propagation. - - Args: - c (Tensor): Input tensor (B, channels, T). - - Returns: - Tensor: Output tensor (B, chennels, T). - - """ - return self.stack(c) + self.skip_layer(c) diff --git a/spaces/kevinwang676/test-1/infer_pack/models_onnx_moess.py b/spaces/kevinwang676/test-1/infer_pack/models_onnx_moess.py deleted file mode 100644 index 12efb0629a2e3d0d746a34f467254536c2bdbe5f..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/test-1/infer_pack/models_onnx_moess.py +++ /dev/null @@ -1,849 +0,0 @@ -import math, pdb, os -from time import time as ttime -import torch -from torch import nn -from torch.nn import functional as F -from infer_pack import modules -from infer_pack import attentions -from infer_pack import commons -from infer_pack.commons import init_weights, get_padding -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from infer_pack.commons import init_weights -import numpy as np -from infer_pack import commons - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder256Sim(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - x = self.proj(x) * x_mask - return x, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMs256NSFsidM(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, pitch, nsff0, sid, rnd, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * rnd) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g) - return o - - -class SynthesizerTrnMs256NSFsid_sim(nn.Module): - """ - Synthesizer for Training - """ - - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - # hop_length, - gin_channels=0, - use_sdp=True, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256Sim( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - is_half=kwargs["is_half"], - ) - - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, ds, max_len=None - ): # y是spec不需要了现在 - g = self.emb_g(ds.unsqueeze(0)).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - x, x_mask = self.enc_p(phone, pitch, phone_lengths) - x = self.flow(x, x_mask, g=g, reverse=True) - o = self.dec((x * x_mask)[:, :, :max_len], pitchf, g=g) - return o - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/configs/_base_/datasets/cityscapes.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/configs/_base_/datasets/cityscapes.py deleted file mode 100644 index f21867c63e1835f6fceb61f066e802fd8fd2a735..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/configs/_base_/datasets/cityscapes.py +++ /dev/null @@ -1,54 +0,0 @@ -# dataset settings -dataset_type = 'CityscapesDataset' -data_root = 'data/cityscapes/' -img_norm_cfg = dict( - mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) -crop_size = (512, 1024) -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations'), - dict(type='Resize', img_scale=(2048, 1024), ratio_range=(0.5, 2.0)), - dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75), - dict(type='RandomFlip', prob=0.5), - dict(type='PhotoMetricDistortion'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255), - dict(type='DefaultFormatBundle'), - dict(type='Collect', keys=['img', 'gt_semantic_seg']), -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(2048, 1024), - # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] -data = dict( - samples_per_gpu=2, - workers_per_gpu=2, - train=dict( - type=dataset_type, - data_root=data_root, - img_dir='leftImg8bit/train', - ann_dir='gtFine/train', - pipeline=train_pipeline), - val=dict( - type=dataset_type, - data_root=data_root, - img_dir='leftImg8bit/val', - ann_dir='gtFine/val', - pipeline=test_pipeline), - test=dict( - type=dataset_type, - data_root=data_root, - img_dir='leftImg8bit/val', - ann_dir='gtFine/val', - pipeline=test_pipeline)) diff --git a/spaces/kiyer/pathfinder/app.py b/spaces/kiyer/pathfinder/app.py deleted file mode 100644 index edbc260b2cd66117b6be9235c3832fc41bef2383..0000000000000000000000000000000000000000 --- a/spaces/kiyer/pathfinder/app.py +++ /dev/null @@ -1,48 +0,0 @@ -import streamlit as st - -st.set_page_config( - page_title="arXiv-GPT", - page_icon="👋", -) - -st.write("# Welcome to arXiv-GPT! 👋") - -st.sidebar.success("Select a function above.") -st.sidebar.markdown("Current functions include visualizing papers in the arxiv embedding, searching for similar papers to an input paper or prompt phrase, or answering quick questions.") - -st.markdown( - """ - arXiv+GPT is a framework for searching and visualizing papers on - the [arXiv](https://arxiv.org/) using the context sensitivity from modern - large language models (LLMs) to better link paper contexts - - **👈 Select a tool from the sidebar** to see some examples - of what this framework can do! - - ### Page summary: - - `Paper search` looks for relevant papers given an arxiv id or a question. - - `Arxiv embedding` shows the landscape of current galaxy evolution papers (astro-ph.GA) - - `QA sources` brings it all together to give concise answers to questions with primary sources and relevant papers. - """ -) - -st.image('https://drive.google.com/uc?id=1yQQCdlgnFzi-_yOMplGIqEyPKJhIsZpO&export=download') - -st.markdown( - """ - ### Coming soon: - - [AstroLLaMA](https://huggingface.co/spaces/universeTBD/astrollama) embeddings! - - export results - - daily updates to repo - - other fields apart from `astro-ph.GA` - - ### Want to learn more? - - Check out `AstroLLaMA` [paper](https://huggingface.co/papers/2309.06126) - - Check out `chaotic_neural` [(link)](http://chaotic-neural.readthedocs.io/) - - Jump into our [documentation](https://docs.streamlit.io) - - Contribute! - - arXiv+GPT is developed and maintained by [UniverseTBD](https://universetbd.org/). Updates on [huggingface](https://huggingface.co/universeTBD) or [twitter](https://twitter.com/universe_tbd). - -""" -) diff --git a/spaces/klenovich/df1/README.md b/spaces/klenovich/df1/README.md deleted file mode 100644 index fe8f02d24e720fa9232f5de49640f3bd986e731c..0000000000000000000000000000000000000000 --- a/spaces/klenovich/df1/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Df1 -emoji: 👁 -colorFrom: yellow -colorTo: blue -sdk: gradio -sdk_version: 3.43.2 -app_file: app.py -pinned: false -license: bigscience-openrail-m ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/kukuhtw/AutoGPT/scripts/check_requirements.py b/spaces/kukuhtw/AutoGPT/scripts/check_requirements.py deleted file mode 100644 index e4eab024a6280c0d54110c69b2e03de639325fa6..0000000000000000000000000000000000000000 --- a/spaces/kukuhtw/AutoGPT/scripts/check_requirements.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys - -import pkg_resources - - -def main(): - requirements_file = sys.argv[1] - with open(requirements_file, "r") as f: - required_packages = [ - line.strip().split("#")[0].strip() for line in f.readlines() - ] - - installed_packages = [package.key for package in pkg_resources.working_set] - - missing_packages = [] - for package in required_packages: - if not package: # Skip empty lines - continue - package_name = package.strip().split("==")[0] - if package_name.lower() not in installed_packages: - missing_packages.append(package_name) - - if missing_packages: - print("Missing packages:") - print(", ".join(missing_packages)) - sys.exit(1) - else: - print("All packages are installed.") - - -if __name__ == "__main__": - main() diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/attr/__init__.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/attr/__init__.py deleted file mode 100644 index 7cfa792f744b7e0b4e28a536c0603f142ded6518..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/attr/__init__.py +++ /dev/null @@ -1,132 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -Classes Without Boilerplate -""" - -from functools import partial -from typing import Callable - -from . import converters, exceptions, filters, setters, validators -from ._cmp import cmp_using -from ._config import get_run_validators, set_run_validators -from ._funcs import asdict, assoc, astuple, evolve, has, resolve_types -from ._make import ( - NOTHING, - Attribute, - Factory, - attrib, - attrs, - fields, - fields_dict, - make_class, - validate, -) -from ._next_gen import define, field, frozen, mutable -from ._version_info import VersionInfo - - -s = attributes = attrs -ib = attr = attrib -dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) - - -class AttrsInstance: - pass - - -__all__ = [ - "Attribute", - "AttrsInstance", - "Factory", - "NOTHING", - "asdict", - "assoc", - "astuple", - "attr", - "attrib", - "attributes", - "attrs", - "cmp_using", - "converters", - "define", - "evolve", - "exceptions", - "field", - "fields", - "fields_dict", - "filters", - "frozen", - "get_run_validators", - "has", - "ib", - "make_class", - "mutable", - "resolve_types", - "s", - "set_run_validators", - "setters", - "validate", - "validators", -] - - -def _make_getattr(mod_name: str) -> Callable: - """ - Create a metadata proxy for packaging information that uses *mod_name* in - its warnings and errors. - """ - - def __getattr__(name: str) -> str: - dunder_to_metadata = { - "__title__": "Name", - "__copyright__": "", - "__version__": "version", - "__version_info__": "version", - "__description__": "summary", - "__uri__": "", - "__url__": "", - "__author__": "", - "__email__": "", - "__license__": "license", - } - if name not in dunder_to_metadata.keys(): - raise AttributeError(f"module {mod_name} has no attribute {name}") - - import sys - import warnings - - if sys.version_info < (3, 8): - from importlib_metadata import metadata - else: - from importlib.metadata import metadata - - if name != "__version_info__": - warnings.warn( - f"Accessing {mod_name}.{name} is deprecated and will be " - "removed in a future release. Use importlib.metadata directly " - "to query for attrs's packaging metadata.", - DeprecationWarning, - stacklevel=2, - ) - - meta = metadata("attrs") - if name == "__license__": - return "MIT" - elif name == "__copyright__": - return "Copyright (c) 2015 Hynek Schlawack" - elif name in ("__uri__", "__url__"): - return meta["Project-URL"].split(" ", 1)[-1] - elif name == "__version_info__": - return VersionInfo._from_version_string(meta["version"]) - elif name == "__author__": - return meta["Author-email"].rsplit(" ", 1)[0] - elif name == "__email__": - return meta["Author-email"].rsplit("<", 1)[1][:-1] - - return meta[dunder_to_metadata[name]] - - return __getattr__ - - -__getattr__ = _make_getattr(__name__) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/components.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/components.py deleted file mode 100644 index b1afb2dad04210f49234a676e4b79a681904ecaf..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/components.py +++ /dev/null @@ -1,6374 +0,0 @@ -"""Contains all of the components that can be used with Gradio Interface / Blocks. -Along with the docs for each component, you can find the names of example demos that use -each component. These demos are located in the `demo` directory.""" - -from __future__ import annotations - -import hashlib -import inspect -import json -import math -import operator -import os -import random -import secrets -import shutil -import tempfile -import urllib.request -import warnings -from copy import deepcopy -from enum import Enum -from pathlib import Path -from types import ModuleType -from typing import TYPE_CHECKING, Any, Callable, Dict - -import aiofiles -import altair as alt -import numpy as np -import pandas as pd -import PIL -import PIL.ImageOps -import requests -from fastapi import UploadFile -from ffmpy import FFmpeg -from gradio_client import media_data -from gradio_client import utils as client_utils -from gradio_client.data_classes import FileData -from gradio_client.documentation import document, set_documentation_group -from gradio_client.serializing import ( - BooleanSerializable, - FileSerializable, - GallerySerializable, - ImgSerializable, - JSONSerializable, - ListStringSerializable, - NumberSerializable, - Serializable, - SimpleSerializable, - StringSerializable, - VideoSerializable, -) -from pandas.api.types import is_numeric_dtype -from PIL import Image as _Image # using _ to minimize namespace pollution -from typing_extensions import Literal - -from gradio import processing_utils, utils -from gradio.blocks import Block, BlockContext -from gradio.events import ( - Blurrable, - Changeable, - Clearable, - Clickable, - Editable, - EventListener, - EventListenerMethod, - Inputable, - Playable, - Releaseable, - Selectable, - Streamable, - Submittable, - Uploadable, -) -from gradio.interpretation import NeighborInterpretable, TokenInterpretable -from gradio.layouts import Column, Form, Row - -if TYPE_CHECKING: - from typing import TypedDict - - class DataframeData(TypedDict): - headers: list[str] - data: list[list[str | int | bool]] - - -set_documentation_group("component") -_Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843 - - -class _Keywords(Enum): - NO_VALUE = "NO_VALUE" # Used as a sentinel to determine if nothing is provided as a argument for `value` in `Component.update()` - FINISHED_ITERATING = "FINISHED_ITERATING" # Used to skip processing of a component's value (needed for generators + state) - - -class Component(Block, Serializable): - """ - A base class for defining the methods that all gradio components should have. - """ - - def __init__(self, *args, **kwargs): - Block.__init__(self, *args, **kwargs) - EventListener.__init__(self) - - def __str__(self): - return self.__repr__() - - def __repr__(self): - return f"{self.get_block_name()}" - - def get_config(self): - """ - :return: a dictionary with context variables for the javascript file associated with the context - """ - return { - "name": self.get_block_name(), - **super().get_config(), - } - - def preprocess(self, x: Any) -> Any: - """ - Any preprocessing needed to be performed on function input. - """ - return x - - def postprocess(self, y): - """ - Any postprocessing needed to be performed on function output. - """ - return y - - def style( - self, - *, - container: bool | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the component. - Parameters: - container: If True, will place the component in a container - providing some extra padding around the border. - """ - put_deprecated_params_in_box = False - if "rounded" in kwargs: - warnings.warn( - "'rounded' styling is no longer supported. To round adjacent components together, place them in a Column(variant='box')." - ) - if isinstance(kwargs["rounded"], (list, tuple)): - put_deprecated_params_in_box = True - kwargs.pop("rounded") - if "margin" in kwargs: - warnings.warn( - "'margin' styling is no longer supported. To place adjacent components together without margin, place them in a Column(variant='box')." - ) - if isinstance(kwargs["margin"], (list, tuple)): - put_deprecated_params_in_box = True - kwargs.pop("margin") - if "border" in kwargs: - warnings.warn( - "'border' styling is no longer supported. To place adjacent components in a shared border, place them in a Column(variant='box')." - ) - kwargs.pop("border") - if container is not None: - self._style["container"] = container - if len(kwargs): - for key in kwargs: - warnings.warn(f"Unknown style parameter: {key}") - if ( - put_deprecated_params_in_box - and isinstance(self.parent, (Row, Column)) - and self.parent.variant == "default" - ): - self.parent.variant = "compact" - return self - - -class IOComponent(Component): - """ - A base class for defining methods that all input/output components should have. - """ - - def __init__( - self, - *, - value: Any = None, - label: str | None = None, - info: str | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - load_fn: Callable | None = None, - every: float | None = None, - **kwargs, - ): - self.temp_files: set[str] = set() - self.DEFAULT_TEMP_DIR = os.environ.get("GRADIO_TEMP_DIR") or str( - Path(tempfile.gettempdir()) / "gradio" - ) - - Component.__init__( - self, elem_id=elem_id, elem_classes=elem_classes, visible=visible, **kwargs - ) - - self.label = label - self.info = info - self.show_label = show_label - self.interactive = interactive - - # load_event is set in the Blocks.attach_load_events method - self.load_event: None | dict[str, Any] = None - self.load_event_to_attach = None - load_fn, initial_value = self.get_load_fn_and_initial_value(value) - self.value = ( - initial_value - if self._skip_init_processing - else self.postprocess(initial_value) - ) - if callable(load_fn): - self.attach_load_event(load_fn, every) - - @staticmethod - def hash_file(file_path: str, chunk_num_blocks: int = 128) -> str: - sha1 = hashlib.sha1() - with open(file_path, "rb") as f: - for chunk in iter(lambda: f.read(chunk_num_blocks * sha1.block_size), b""): - sha1.update(chunk) - return sha1.hexdigest() - - @staticmethod - def hash_url(url: str, chunk_num_blocks: int = 128) -> str: - sha1 = hashlib.sha1() - remote = urllib.request.urlopen(url) - max_file_size = 100 * 1024 * 1024 # 100MB - total_read = 0 - while True: - data = remote.read(chunk_num_blocks * sha1.block_size) - total_read += chunk_num_blocks * sha1.block_size - if not data or total_read > max_file_size: - break - sha1.update(data) - return sha1.hexdigest() - - @staticmethod - def hash_bytes(bytes: bytes): - sha1 = hashlib.sha1() - sha1.update(bytes) - return sha1.hexdigest() - - @staticmethod - def hash_base64(base64_encoding: str, chunk_num_blocks: int = 128) -> str: - sha1 = hashlib.sha1() - for i in range(0, len(base64_encoding), chunk_num_blocks * sha1.block_size): - data = base64_encoding[i : i + chunk_num_blocks * sha1.block_size] - sha1.update(data.encode("utf-8")) - return sha1.hexdigest() - - def make_temp_copy_if_needed(self, file_path: str) -> str: - """Returns a temporary file path for a copy of the given file path if it does - not already exist. Otherwise returns the path to the existing temp file.""" - temp_dir = self.hash_file(file_path) - temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir - temp_dir.mkdir(exist_ok=True, parents=True) - - name = client_utils.strip_invalid_filename_characters(Path(file_path).name) - full_temp_file_path = str(utils.abspath(temp_dir / name)) - - if not Path(full_temp_file_path).exists(): - shutil.copy2(file_path, full_temp_file_path) - - self.temp_files.add(full_temp_file_path) - return full_temp_file_path - - async def save_uploaded_file(self, file: UploadFile, upload_dir: str) -> str: - temp_dir = secrets.token_hex( - 20 - ) # Since the full file is being uploaded anyways, there is no benefit to hashing the file. - temp_dir = Path(upload_dir) / temp_dir - temp_dir.mkdir(exist_ok=True, parents=True) - - if file.filename: - file_name = Path(file.filename).name - name = client_utils.strip_invalid_filename_characters(file_name) - else: - name = f"tmp{secrets.token_hex(5)}" - - full_temp_file_path = str(utils.abspath(temp_dir / name)) - - async with aiofiles.open(full_temp_file_path, "wb") as output_file: - while True: - content = await file.read(100 * 1024 * 1024) - if not content: - break - await output_file.write(content) - - return full_temp_file_path - - def download_temp_copy_if_needed(self, url: str) -> str: - """Downloads a file and makes a temporary file path for a copy if does not already - exist. Otherwise returns the path to the existing temp file.""" - temp_dir = self.hash_url(url) - temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir - temp_dir.mkdir(exist_ok=True, parents=True) - - name = client_utils.strip_invalid_filename_characters(Path(url).name) - full_temp_file_path = str(utils.abspath(temp_dir / name)) - - if not Path(full_temp_file_path).exists(): - with requests.get(url, stream=True) as r, open( - full_temp_file_path, "wb" - ) as f: - shutil.copyfileobj(r.raw, f) - - self.temp_files.add(full_temp_file_path) - return full_temp_file_path - - def base64_to_temp_file_if_needed( - self, base64_encoding: str, file_name: str | None = None - ) -> str: - """Converts a base64 encoding to a file and returns the path to the file if - the file doesn't already exist. Otherwise returns the path to the existing file. - """ - temp_dir = self.hash_base64(base64_encoding) - temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir - temp_dir.mkdir(exist_ok=True, parents=True) - - guess_extension = client_utils.get_extension(base64_encoding) - if file_name: - file_name = client_utils.strip_invalid_filename_characters(file_name) - elif guess_extension: - file_name = f"file.{guess_extension}" - else: - file_name = "file" - - full_temp_file_path = str(utils.abspath(temp_dir / file_name)) # type: ignore - - if not Path(full_temp_file_path).exists(): - data, _ = client_utils.decode_base64_to_binary(base64_encoding) - with open(full_temp_file_path, "wb") as fb: - fb.write(data) - - self.temp_files.add(full_temp_file_path) - return full_temp_file_path - - def pil_to_temp_file(self, img: _Image.Image, dir: str, format="png") -> str: - bytes_data = processing_utils.encode_pil_to_bytes(img, format) - temp_dir = Path(dir) / self.hash_bytes(bytes_data) - temp_dir.mkdir(exist_ok=True, parents=True) - filename = str(temp_dir / f"image.{format}") - img.save(filename, pnginfo=processing_utils.get_pil_metadata(img)) - return filename - - def img_array_to_temp_file(self, arr: np.ndarray, dir: str) -> str: - pil_image = _Image.fromarray( - processing_utils._convert(arr, np.uint8, force_copy=False) - ) - return self.pil_to_temp_file(pil_image, dir, format="png") - - def audio_to_temp_file( - self, data: np.ndarray, sample_rate: int, dir: str, format: str - ): - temp_dir = Path(dir) / self.hash_bytes(data.tobytes()) - temp_dir.mkdir(exist_ok=True, parents=True) - filename = str(temp_dir / f"audio.{format}") - processing_utils.audio_to_file(sample_rate, data, filename, format=format) - return filename - - def file_bytes_to_file(self, data: bytes, dir: str, file_name: str): - path = Path(dir) / self.hash_bytes(data) - path.mkdir(exist_ok=True, parents=True) - path = path / Path(file_name).name - path.write_bytes(data) - return path - - def get_config(self): - config = { - "label": self.label, - "show_label": self.show_label, - "interactive": self.interactive, - **super().get_config(), - } - if self.info: - config["info"] = self.info - return config - - @staticmethod - def get_load_fn_and_initial_value(value): - if callable(value): - initial_value = value() - load_fn = value - else: - initial_value = value - load_fn = None - return load_fn, initial_value - - def attach_load_event(self, callable: Callable, every: float | None): - """Add a load event that runs `callable`, optionally every `every` seconds.""" - self.load_event_to_attach = (callable, every) - - def as_example(self, input_data): - """Return the input data in a way that can be displayed by the examples dataset component in the front-end.""" - return input_data - - -class FormComponent: - def get_expected_parent(self) -> type[Form]: - return Form - - -@document("style") -class Textbox( - FormComponent, - Changeable, - Inputable, - Selectable, - Submittable, - Blurrable, - IOComponent, - StringSerializable, - TokenInterpretable, -): - """ - Creates a textarea for user to enter string input or display string output. - Preprocessing: passes textarea value as a {str} into the function. - Postprocessing: expects a {str} returned from function and sets textarea value to it. - Examples-format: a {str} representing the textbox input. - - Demos: hello_world, diff_texts, sentence_builder - Guides: creating-a-chatbot, real-time-speech-recognition - """ - - def __init__( - self, - value: str | Callable | None = "", - *, - lines: int = 1, - max_lines: int = 20, - placeholder: str | None = None, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - type: str = "text", - **kwargs, - ): - """ - Parameters: - value: default text to provide in textarea. If callable, the function will be called whenever the app loads to set the initial value of the component. - lines: minimum number of line rows to provide in textarea. - max_lines: maximum number of line rows to provide in textarea. - placeholder: placeholder hint to provide behind textarea. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - type: The type of textbox. One of: 'text', 'password', 'email', Default is 'text'. - """ - if type not in ["text", "password", "email"]: - raise ValueError('`type` must be one of "text", "password", or "email".') - - # - self.lines = lines - if type == "text": - self.max_lines = max(lines, max_lines) - else: - self.max_lines = 1 - self.placeholder = placeholder - self.select: EventListenerMethod - """ - Event listener for when the user selects text in the Textbox. - Uses event data gradio.SelectData to carry `value` referring to selected substring, and `index` tuple referring to selected range endpoints. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - TokenInterpretable.__init__(self) - self.cleared_value = "" - self.type = type - - def get_config(self): - return { - "lines": self.lines, - "max_lines": self.max_lines, - "placeholder": self.placeholder, - "value": self.value, - "type": self.type, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - lines: int | None = None, - max_lines: int | None = None, - placeholder: str | None = None, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - interactive: bool | None = None, - type: str | None = None, - ): - return { - "lines": lines, - "max_lines": max_lines, - "placeholder": placeholder, - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "type": type, - "interactive": interactive, - "__type__": "update", - } - - def preprocess(self, x: str | None) -> str | None: - """ - Preprocesses input (converts it to a string) before passing it to the function. - Parameters: - x: text - Returns: - text - """ - return None if x is None else str(x) - - def postprocess(self, y: str | None) -> str | None: - """ - Postproccess the function output y by converting it to a str before passing it to the frontend. - Parameters: - y: function output to postprocess. - Returns: - text - """ - return None if y is None else str(y) - - def set_interpret_parameters( - self, separator: str = " ", replacement: str | None = None - ): - """ - Calculates interpretation score of characters in input by splitting input into tokens, then using a "leave one out" method to calculate the score of each token by removing each token and measuring the delta of the output value. - Parameters: - separator: Separator to use to split input into tokens. - replacement: In the "leave one out" step, the text that the token should be replaced with. If None, the token is removed altogether. - """ - self.interpretation_separator = separator - self.interpretation_replacement = replacement - return self - - def tokenize(self, x: str) -> tuple[list[str], list[str], None]: - """ - Tokenizes an input string by dividing into "words" delimited by self.interpretation_separator - """ - tokens = x.split(self.interpretation_separator) - leave_one_out_strings = [] - for index in range(len(tokens)): - leave_one_out_set = list(tokens) - if self.interpretation_replacement is None: - leave_one_out_set.pop(index) - else: - leave_one_out_set[index] = self.interpretation_replacement - leave_one_out_strings.append( - self.interpretation_separator.join(leave_one_out_set) - ) - return tokens, leave_one_out_strings, None - - def get_masked_inputs( - self, tokens: list[str], binary_mask_matrix: list[list[int]] - ) -> list[str]: - """ - Constructs partially-masked sentences for SHAP interpretation - """ - masked_inputs = [] - for binary_mask_vector in binary_mask_matrix: - masked_input = np.array(tokens)[np.array(binary_mask_vector, dtype=bool)] - masked_inputs.append(self.interpretation_separator.join(masked_input)) - return masked_inputs - - def get_interpretation_scores( - self, x, neighbors, scores: list[float], tokens: list[str], masks=None, **kwargs - ) -> list[tuple[str, float]]: - """ - Returns: - Each tuple set represents a set of characters and their corresponding interpretation score. - """ - result = [] - for token, score in zip(tokens, scores): - result.append((token, score)) - result.append((self.interpretation_separator, 0)) - return result - - def style( - self, - *, - show_copy_button: bool | None = None, - container: bool | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the Textbox component. - Parameters: - show_copy_button: If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True. - container: If True, will place the component in a container - providing some extra padding around the border. - """ - if show_copy_button is not None: - self._style["show_copy_button"] = show_copy_button - - return Component.style(self, container=container, **kwargs) - - -@document("style") -class Number( - FormComponent, - Changeable, - Inputable, - Submittable, - Blurrable, - IOComponent, - NumberSerializable, - NeighborInterpretable, -): - """ - Creates a numeric field for user to enter numbers as input or display numeric output. - Preprocessing: passes field value as a {float} or {int} into the function, depending on `precision`. - Postprocessing: expects an {int} or {float} returned from the function and sets field value to it. - Examples-format: a {float} or {int} representing the number's value. - - Demos: tax_calculator, titanic_survival, blocks_simple_squares - """ - - def __init__( - self, - value: float | Callable | None = None, - *, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - precision: int | None = None, - **kwargs, - ): - """ - Parameters: - value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will be editable; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - precision: Precision to round input/output to. If set to 0, will round to nearest integer and convert type to int. If None, no rounding happens. - """ - self.precision = precision - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - NeighborInterpretable.__init__(self) - - @staticmethod - def _round_to_precision(num: float | int, precision: int | None) -> float | int: - """ - Round to a given precision. - - If precision is None, no rounding happens. If 0, num is converted to int. - - Parameters: - num: Number to round. - precision: Precision to round to. - Returns: - rounded number - """ - if precision is None: - return float(num) - elif precision == 0: - return int(round(num, precision)) - else: - return round(num, precision) - - def get_config(self): - return { - "value": self.value, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "interactive": interactive, - "__type__": "update", - } - - def preprocess(self, x: float | None) -> float | None: - """ - Parameters: - x: numeric input - Returns: - number representing function input - """ - if x is None: - return None - return self._round_to_precision(x, self.precision) - - def postprocess(self, y: float | None) -> float | None: - """ - Any postprocessing needed to be performed on function output. - - Parameters: - y: numeric output - Returns: - number representing function output - """ - if y is None: - return None - return self._round_to_precision(y, self.precision) - - def set_interpret_parameters( - self, steps: int = 3, delta: float = 1, delta_type: str = "percent" - ): - """ - Calculates interpretation scores of numeric values close to the input number. - Parameters: - steps: Number of nearby values to measure in each direction (above and below the input number). - delta: Size of step in each direction between nearby values. - delta_type: "percent" if delta step between nearby values should be a calculated as a percent, or "absolute" if delta should be a constant step change. - """ - self.interpretation_steps = steps - self.interpretation_delta = delta - self.interpretation_delta_type = delta_type - return self - - def get_interpretation_neighbors(self, x: float | int) -> tuple[list[float], dict]: - x = self._round_to_precision(x, self.precision) - if self.interpretation_delta_type == "percent": - delta = 1.0 * self.interpretation_delta * x / 100 - elif self.interpretation_delta_type == "absolute": - delta = self.interpretation_delta - else: - delta = self.interpretation_delta - if self.precision == 0 and math.floor(delta) != delta: - raise ValueError( - f"Delta value {delta} is not an integer and precision=0. Cannot generate valid set of neighbors. " - "If delta_type='percent', pick a value of delta such that x * delta is an integer. " - "If delta_type='absolute', pick a value of delta that is an integer." - ) - # run_interpretation will preprocess the neighbors so no need to convert to int here - negatives = ( - np.array(x) + np.arange(-self.interpretation_steps, 0) * delta - ).tolist() - positives = ( - np.array(x) + np.arange(1, self.interpretation_steps + 1) * delta - ).tolist() - return negatives + positives, {} - - def get_interpretation_scores( - self, x: float, neighbors: list[float], scores: list[float | None], **kwargs - ) -> list[tuple[float, float | None]]: - """ - Returns: - Each tuple set represents a numeric value near the input and its corresponding interpretation score. - """ - interpretation = list(zip(neighbors, scores)) - interpretation.insert(int(len(interpretation) / 2), (x, None)) - return interpretation - - -@document("style") -class Slider( - FormComponent, - Changeable, - Inputable, - Releaseable, - IOComponent, - NumberSerializable, - NeighborInterpretable, -): - """ - Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`. - Preprocessing: passes slider value as a {float} into the function. - Postprocessing: expects an {int} or {float} returned from function and sets slider value to it as long as it is within range. - Examples-format: A {float} or {int} representing the slider's value. - - Demos: sentence_builder, slider_release, generate_tone, titanic_survival, interface_random_slider, blocks_random_slider - Guides: create-your-own-friends-with-a-gan - """ - - def __init__( - self, - minimum: float = 0, - maximum: float = 100, - value: float | Callable | None = None, - *, - step: float | None = None, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - randomize: bool = False, - **kwargs, - ): - """ - Parameters: - minimum: minimum value for slider. - maximum: maximum value for slider. - value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True. - step: increment between slider values. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - randomize: If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum. - """ - self.minimum = minimum - self.maximum = maximum - if step is None: - difference = maximum - minimum - power = math.floor(math.log10(difference) - 2) - self.step = 10**power - else: - self.step = step - if randomize: - value = self.get_random_value - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - NeighborInterpretable.__init__(self) - self.cleared_value = self.value - - def api_info(self) -> dict[str, dict | bool]: - return { - "info": { - "type": "number", - "description": f"numeric value between {self.minimum} and {self.maximum}", - }, - "serialized_info": False, - } - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": self.minimum, - "serialized": self.minimum, - } - - def get_config(self): - return { - "minimum": self.minimum, - "maximum": self.maximum, - "step": self.step, - "value": self.value, - **IOComponent.get_config(self), - } - - def get_random_value(self): - n_steps = int((self.maximum - self.minimum) / self.step) - step = random.randint(0, n_steps) - value = self.minimum + step * self.step - # Round to number of decimals in step so that UI doesn't display long decimals - n_decimals = max(str(self.step)[::-1].find("."), 0) - if n_decimals: - value = round(value, n_decimals) - return value - - @staticmethod - def update( - value: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - minimum: float | None = None, - maximum: float | None = None, - step: float | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "minimum": minimum, - "maximum": maximum, - "step": step, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def postprocess(self, y: float | None) -> float | None: - """ - Any postprocessing needed to be performed on function output. - Parameters: - y: numeric output - Returns: - numeric output or minimum number if None - """ - return self.minimum if y is None else y - - def set_interpret_parameters(self, steps: int = 8) -> Slider: - """ - Calculates interpretation scores of numeric values ranging between the minimum and maximum values of the slider. - Parameters: - steps: Number of neighboring values to measure between the minimum and maximum values of the slider range. - """ - self.interpretation_steps = steps - return self - - def get_interpretation_neighbors(self, x) -> tuple[object, dict]: - return ( - np.linspace(self.minimum, self.maximum, self.interpretation_steps).tolist(), - {}, - ) - - def style( - self, - *, - container: bool | None = None, - ): - """ - This method can be used to change the appearance of the slider. - Parameters: - container: If True, will place the component in a container - providing some extra padding around the border. - """ - Component.style( - self, - container=container, - ) - return self - - -@document("style") -class Checkbox( - FormComponent, - Changeable, - Inputable, - Selectable, - IOComponent, - BooleanSerializable, - NeighborInterpretable, -): - """ - Creates a checkbox that can be set to `True` or `False`. - - Preprocessing: passes the status of the checkbox as a {bool} into the function. - Postprocessing: expects a {bool} returned from the function and, if it is True, checks the checkbox. - Examples-format: a {bool} representing whether the box is checked. - Demos: sentence_builder, titanic_survival - """ - - def __init__( - self, - value: bool | Callable = False, - *, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: if True, checked by default. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, this checkbox can be checked; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.select: EventListenerMethod - """ - Event listener for when the user selects or deselects Checkbox. - Uses event data gradio.SelectData to carry `value` referring to label of checkbox, and `selected` to refer to state of checkbox. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - NeighborInterpretable.__init__(self) - - def get_config(self): - return { - "value": self.value, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: bool | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def get_interpretation_neighbors(self, x): - return [not x], {} - - def get_interpretation_scores(self, x, neighbors, scores, **kwargs): - """ - Returns: - The first value represents the interpretation score if the input is False, and the second if the input is True. - """ - if x: - return scores[0], None - else: - return None, scores[0] - - -@document("style") -class CheckboxGroup( - FormComponent, - Changeable, - Inputable, - Selectable, - IOComponent, - ListStringSerializable, - NeighborInterpretable, -): - """ - Creates a set of checkboxes of which a subset can be checked. - Preprocessing: passes the list of checked checkboxes as a {List[str]} or their indices as a {List[int]} into the function, depending on `type`. - Postprocessing: expects a {List[str]}, each element of which becomes a checked checkbox. - Examples-format: a {List[str]} representing the values to be checked. - Demos: sentence_builder, titanic_survival - """ - - def __init__( - self, - choices: list[str] | None = None, - *, - value: list[str] | str | Callable | None = None, - type: str = "value", - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - choices: list of options to select from. - value: default selected list of options. If callable, the function will be called whenever the app loads to set the initial value of the component. - type: Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indices of the choices selected. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.choices = choices or [] - self.cleared_value = [] - valid_types = ["value", "index"] - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - self.type = type - self.select: EventListenerMethod - """ - Event listener for when the user selects or deselects within CheckboxGroup. - Uses event data gradio.SelectData to carry `value` referring to label of selected checkbox, `index` to refer to index, and `selected` to refer to state of checkbox. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - NeighborInterpretable.__init__(self) - - def get_config(self): - return { - "choices": self.choices, - "value": self.value, - **IOComponent.get_config(self), - } - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": self.choices[0] if self.choices else None, - "serialized": self.choices[0] if self.choices else None, - } - - @staticmethod - def update( - value: list[str] - | str - | Literal[_Keywords.NO_VALUE] - | None = _Keywords.NO_VALUE, - choices: list[str] | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "choices": choices, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess(self, x: list[str]) -> list[str] | list[int]: - """ - Parameters: - x: list of selected choices - Returns: - list of selected choices as strings or indices within choice list - """ - if self.type == "value": - return x - elif self.type == "index": - return [self.choices.index(choice) for choice in x] - else: - raise ValueError( - f"Unknown type: {self.type}. Please choose from: 'value', 'index'." - ) - - def postprocess(self, y: list[str] | str | None) -> list[str]: - """ - Any postprocessing needed to be performed on function output. - Parameters: - y: List of selected choices. If a single choice is selected, it can be passed in as a string - Returns: - List of selected choices - """ - if y is None: - return [] - if not isinstance(y, list): - y = [y] - return y - - def get_interpretation_neighbors(self, x): - leave_one_out_sets = [] - for choice in self.choices: - leave_one_out_set = list(x) - if choice in leave_one_out_set: - leave_one_out_set.remove(choice) - else: - leave_one_out_set.append(choice) - leave_one_out_sets.append(leave_one_out_set) - return leave_one_out_sets, {} - - def get_interpretation_scores(self, x, neighbors, scores, **kwargs): - """ - Returns: - For each tuple in the list, the first value represents the interpretation score if the input is False, and the second if the input is True. - """ - final_scores = [] - for choice, score in zip(self.choices, scores): - score_set = [score, None] if choice in x else [None, score] - final_scores.append(score_set) - return final_scores - - def style( - self, - *, - item_container: bool | None = None, - container: bool | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the CheckboxGroup. - Parameters: - item_container: If True, will place the items in a container. - container: If True, will place the component in a container - providing some extra padding around the border. - """ - if item_container is not None: - self._style["item_container"] = item_container - - Component.style(self, container=container, **kwargs) - return self - - -@document("style") -class Radio( - FormComponent, - Selectable, - Changeable, - Inputable, - IOComponent, - StringSerializable, - NeighborInterpretable, -): - """ - Creates a set of radio buttons of which only one can be selected. - Preprocessing: passes the value of the selected radio button as a {str} or its index as an {int} into the function, depending on `type`. - Postprocessing: expects a {str} corresponding to the value of the radio button to be selected. - Examples-format: a {str} representing the radio option to select. - - Demos: sentence_builder, titanic_survival, blocks_essay - """ - - def __init__( - self, - choices: list[str] | None = None, - *, - value: str | Callable | None = None, - type: str = "value", - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - choices: list of options to select from. - value: the button selected by default. If None, no button is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component. - type: Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.choices = choices or [] - valid_types = ["value", "index"] - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - self.type = type - self.select: EventListenerMethod - """ - Event listener for when the user selects Radio option. - Uses event data gradio.SelectData to carry `value` referring to label of selected option, and `index` to refer to index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - NeighborInterpretable.__init__(self) - self.cleared_value = self.value - - def get_config(self): - return { - "choices": self.choices, - "value": self.value, - **IOComponent.get_config(self), - } - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": self.choices[0] if self.choices else None, - "serialized": self.choices[0] if self.choices else None, - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - choices: list[str] | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "choices": choices, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess(self, x: str | None) -> str | int | None: - """ - Parameters: - x: selected choice - Returns: - selected choice as string or index within choice list - """ - if self.type == "value": - return x - elif self.type == "index": - if x is None: - return None - else: - return self.choices.index(x) - else: - raise ValueError( - f"Unknown type: {self.type}. Please choose from: 'value', 'index'." - ) - - def get_interpretation_neighbors(self, x): - choices = list(self.choices) - choices.remove(x) - return choices, {} - - def get_interpretation_scores( - self, x, neighbors, scores: list[float | None], **kwargs - ) -> list: - """ - Returns: - Each value represents the interpretation score corresponding to each choice. - """ - scores.insert(self.choices.index(x), None) - return scores - - def style( - self, - *, - item_container: bool | None = None, - container: bool | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the radio component. - Parameters: - item_container: If True, will place items in a container. - container: If True, will place the component in a container - providing some extra padding around the border. - """ - if item_container is not None: - self._style["item_container"] = item_container - - Component.style(self, container=container, **kwargs) - return self - - -@document("style") -class Dropdown( - Changeable, - Inputable, - Selectable, - Blurrable, - IOComponent, - SimpleSerializable, - FormComponent, -): - """ - Creates a dropdown of choices from which entries can be selected. - Preprocessing: passes the value of the selected dropdown entry as a {str} or its index as an {int} into the function, depending on `type`. - Postprocessing: expects a {str} corresponding to the value of the dropdown entry to be selected. - Examples-format: a {str} representing the drop down value to select. - Demos: sentence_builder, titanic_survival - """ - - def __init__( - self, - choices: list[str] | None = None, - *, - value: str | list[str] | Callable | None = None, - type: str = "value", - multiselect: bool | None = None, - max_choices: int | None = None, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - allow_custom_value: bool = False, - **kwargs, - ): - """ - Parameters: - choices: list of options to select from. - value: default value(s) selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component. - type: Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. - multiselect: if True, multiple choices can be selected. - max_choices: maximum number of choices that can be selected. If None, no limit is enforced. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - allow_custom_value: If True, allows user to enter a custom value that is not in the list of choices. - """ - self.choices = [str(choice) for choice in choices] if choices else [] - valid_types = ["value", "index"] - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - self.type = type - self.multiselect = multiselect - if multiselect and isinstance(value, str): - value = [value] - if not multiselect and max_choices is not None: - warnings.warn( - "The `max_choices` parameter is ignored when `multiselect` is False." - ) - self.max_choices = max_choices - self.allow_custom_value = allow_custom_value - if multiselect and allow_custom_value: - raise ValueError( - "Custom values are not supported when `multiselect` is True." - ) - self.interpret_by_tokens = False - self.select: EventListenerMethod - """ - Event listener for when the user selects Dropdown option. - Uses event data gradio.SelectData to carry `value` referring to label of selected option, and `index` to refer to index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - self.cleared_value = self.value or ([] if multiselect else "") - - def api_info(self) -> dict[str, dict | bool]: - if self.multiselect: - type = { - "type": "array", - "items": {"type": "string"}, - "description": f"List of options from: {self.choices}", - } - else: - type = {"type": "string", "description": f"Option from: {self.choices}"} - return {"info": type, "serialized_info": False} - - def example_inputs(self) -> dict[str, Any]: - if self.multiselect: - return { - "raw": [self.choices[0]] if self.choices else [], - "serialized": [self.choices[0]] if self.choices else [], - } - else: - return { - "raw": self.choices[0] if self.choices else None, - "serialized": self.choices[0] if self.choices else None, - } - - def get_config(self): - return { - "choices": self.choices, - "value": self.value, - "multiselect": self.multiselect, - "max_choices": self.max_choices, - "allow_custom_value": self.allow_custom_value, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - choices: str | list[str] | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - placeholder: str | None = None, - visible: bool | None = None, - ): - return { - "choices": choices, - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "interactive": interactive, - "placeholder": placeholder, - "__type__": "update", - } - - def preprocess( - self, x: str | list[str] - ) -> str | int | list[str] | list[int] | None: - """ - Parameters: - x: selected choice(s) - Returns: - selected choice(s) as string or index within choice list or list of string or indices - """ - if self.type == "value": - return x - elif self.type == "index": - if x is None: - return None - elif self.multiselect: - return [self.choices.index(c) for c in x] - else: - if isinstance(x, str): - return self.choices.index(x) if x in self.choices else None - else: - raise ValueError( - f"Unknown type: {self.type}. Please choose from: 'value', 'index'." - ) - - def set_interpret_parameters(self): - """ - Calculates interpretation score of each choice by comparing the output against each of the outputs when alternative choices are selected. - """ - return self - - def get_interpretation_neighbors(self, x): - choices = list(self.choices) - choices.remove(x) - return choices, {} - - def get_interpretation_scores( - self, x, neighbors, scores: list[float | None], **kwargs - ) -> list: - """ - Returns: - Each value represents the interpretation score corresponding to each choice. - """ - scores.insert(self.choices.index(x), None) - return scores - - def style(self, *, container: bool | None = None, **kwargs): - """ - This method can be used to change the appearance of the Dropdown. - Parameters: - container: If True, will place the component in a container - providing some extra padding around the border. - """ - Component.style(self, container=container, **kwargs) - return self - - -@document("style") -class Image( - Editable, - Clearable, - Changeable, - Streamable, - Selectable, - Uploadable, - IOComponent, - ImgSerializable, - TokenInterpretable, -): - """ - Creates an image component that can be used to upload/draw images (as an input) or display images (as an output). - Preprocessing: passes the uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a {dict} with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`. - Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} or {pathlib.Path} filepath to an image and displays the image. - Examples-format: a {str} filepath to a local file that contains the image. - Demos: image_mod, image_mod_default_image - Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary_app, create-your-own-friends-with-a-gan - """ - - def __init__( - self, - value: str | _Image.Image | np.ndarray | None = None, - *, - shape: tuple[int, int] | None = None, - image_mode: str = "RGB", - invert_colors: bool = False, - source: str = "upload", - tool: str | None = None, - type: str = "numpy", - label: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - streaming: bool = False, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - mirror_webcam: bool = True, - brush_radius: float | None = None, - **kwargs, - ): - """ - Parameters: - value: A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. - shape: (width, height) shape to crop and resize image to; if None, matches input image size. Pass None for either width or height to only crop and resize the other. - image_mode: "RGB" if color, or "L" if black and white. - invert_colors: whether to invert the image as a preprocessing step. - source: Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools. - tool: Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively. - type: The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - mirror_webcam: If True webcam will be mirrored. Default is True. - brush_radius: Size of the brush for Sketch. Default is None which chooses a sensible default - """ - self.brush_radius = brush_radius - self.mirror_webcam = mirror_webcam - valid_types = ["numpy", "pil", "filepath"] - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - self.type = type - self.shape = shape - self.image_mode = image_mode - valid_sources = ["upload", "webcam", "canvas"] - if source not in valid_sources: - raise ValueError( - f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}" - ) - self.source = source - if tool is None: - self.tool = "sketch" if source == "canvas" else "editor" - else: - self.tool = tool - self.invert_colors = invert_colors - self.streaming = streaming - if streaming and source != "webcam": - raise ValueError("Image streaming only available if source is 'webcam'.") - self.select: EventListenerMethod - """ - Event listener for when the user clicks on a pixel within the image. - Uses event data gradio.SelectData to carry `index` to refer to the [x, y] coordinates of the clicked pixel. - See EventData documentation on how to use this event data. - """ - - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - TokenInterpretable.__init__(self) - - def get_config(self): - return { - "image_mode": self.image_mode, - "shape": self.shape, - "source": self.source, - "tool": self.tool, - "value": self.value, - "streaming": self.streaming, - "mirror_webcam": self.mirror_webcam, - "brush_radius": self.brush_radius, - "selectable": self.selectable, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - brush_radius: float | None = None, - ): - return { - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "brush_radius": brush_radius, - "__type__": "update", - } - - def _format_image( - self, im: _Image.Image | None - ) -> np.ndarray | _Image.Image | str | None: - """Helper method to format an image based on self.type""" - if im is None: - return im - fmt = im.format - if self.type == "pil": - return im - elif self.type == "numpy": - return np.array(im) - elif self.type == "filepath": - path = self.pil_to_temp_file( - im, dir=self.DEFAULT_TEMP_DIR, format=fmt or "png" - ) - self.temp_files.add(path) - return path - else: - raise ValueError( - "Unknown type: " - + str(self.type) - + ". Please choose from: 'numpy', 'pil', 'filepath'." - ) - - def preprocess( - self, x: str | dict[str, str] - ) -> np.ndarray | _Image.Image | str | dict | None: - """ - Parameters: - x: base64 url data, or (if tool == "sketch") a dict of image and mask base64 url data - Returns: - image in requested format, or (if tool == "sketch") a dict of image and mask in requested format - """ - if x is None: - return x - - mask = "" - if self.tool == "sketch" and self.source in ["upload", "webcam"]: - assert isinstance(x, dict) - x, mask = x["image"], x["mask"] - - assert isinstance(x, str) - im = processing_utils.decode_base64_to_image(x) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - im = im.convert(self.image_mode) - if self.shape is not None: - im = processing_utils.resize_and_crop(im, self.shape) - if self.invert_colors: - im = PIL.ImageOps.invert(im) - if ( - self.source == "webcam" - and self.mirror_webcam is True - and self.tool != "color-sketch" - ): - im = PIL.ImageOps.mirror(im) - - if self.tool == "sketch" and self.source in ["upload", "webcam"]: - mask_im = processing_utils.decode_base64_to_image(mask) - return { - "image": self._format_image(im), - "mask": self._format_image(mask_im), - } - - return self._format_image(im) - - def postprocess( - self, y: np.ndarray | _Image.Image | str | Path | None - ) -> str | None: - """ - Parameters: - y: image as a numpy array, PIL Image, string/Path filepath, or string URL - Returns: - base64 url data - """ - if y is None: - return None - if isinstance(y, np.ndarray): - return processing_utils.encode_array_to_base64(y) - elif isinstance(y, _Image.Image): - return processing_utils.encode_pil_to_base64(y) - elif isinstance(y, (str, Path)): - return client_utils.encode_url_or_file_to_base64(y) - else: - raise ValueError("Cannot process this value as an Image") - - def set_interpret_parameters(self, segments: int = 16): - """ - Calculates interpretation score of image subsections by splitting the image into subsections, then using a "leave one out" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value. - Parameters: - segments: Number of interpretation segments to split image into. - """ - self.interpretation_segments = segments - return self - - def _segment_by_slic(self, x): - """ - Helper method that segments an image into superpixels using slic. - Parameters: - x: base64 representation of an image - """ - x = processing_utils.decode_base64_to_image(x) - if self.shape is not None: - x = processing_utils.resize_and_crop(x, self.shape) - resized_and_cropped_image = np.array(x) - try: - from skimage.segmentation import slic - except (ImportError, ModuleNotFoundError) as err: - raise ValueError( - "Error: running this interpretation for images requires scikit-image, please install it first." - ) from err - try: - segments_slic = slic( - resized_and_cropped_image, - self.interpretation_segments, - compactness=10, - sigma=1, - start_label=1, - ) - except TypeError: # For skimage 0.16 and older - segments_slic = slic( - resized_and_cropped_image, - self.interpretation_segments, - compactness=10, - sigma=1, - ) - return segments_slic, resized_and_cropped_image - - def tokenize(self, x): - """ - Segments image into tokens, masks, and leave-one-out-tokens - Parameters: - x: base64 representation of an image - Returns: - tokens: list of tokens, used by the get_masked_input() method - leave_one_out_tokens: list of left-out tokens, used by the get_interpretation_neighbors() method - masks: list of masks, used by the get_interpretation_neighbors() method - """ - segments_slic, resized_and_cropped_image = self._segment_by_slic(x) - tokens, masks, leave_one_out_tokens = [], [], [] - replace_color = np.mean(resized_and_cropped_image, axis=(0, 1)) - for segment_value in np.unique(segments_slic): - mask = segments_slic == segment_value - image_screen = np.copy(resized_and_cropped_image) - image_screen[segments_slic == segment_value] = replace_color - leave_one_out_tokens.append( - processing_utils.encode_array_to_base64(image_screen) - ) - token = np.copy(resized_and_cropped_image) - token[segments_slic != segment_value] = 0 - tokens.append(token) - masks.append(mask) - return tokens, leave_one_out_tokens, masks - - def get_masked_inputs(self, tokens, binary_mask_matrix): - masked_inputs = [] - for binary_mask_vector in binary_mask_matrix: - masked_input = np.zeros_like(tokens[0], dtype=int) - for token, b in zip(tokens, binary_mask_vector): - masked_input = masked_input + token * int(b) - masked_inputs.append(processing_utils.encode_array_to_base64(masked_input)) - return masked_inputs - - def get_interpretation_scores( - self, x, neighbors, scores, masks, tokens=None, **kwargs - ) -> list[list[float]]: - """ - Returns: - A 2D array representing the interpretation score of each pixel of the image. - """ - x = processing_utils.decode_base64_to_image(x) - if self.shape is not None: - x = processing_utils.resize_and_crop(x, self.shape) - x = np.array(x) - output_scores = np.zeros((x.shape[0], x.shape[1])) - - for score, mask in zip(scores, masks): - output_scores += score * mask - - max_val, min_val = np.max(output_scores), np.min(output_scores) - if max_val > 0: - output_scores = (output_scores - min_val) / (max_val - min_val) - return output_scores.tolist() - - def style(self, *, height: int | None = None, width: int | None = None, **kwargs): - """ - This method can be used to change the appearance of the Image component. - Parameters: - height: Height of the image. - width: Width of the image. - """ - self._style["height"] = height - self._style["width"] = width - Component.style( - self, - **kwargs, - ) - return self - - def check_streamable(self): - if self.source != "webcam": - raise ValueError("Image streaming only available if source is 'webcam'.") - - def as_example(self, input_data: str | None) -> str: - if input_data is None: - return "" - elif ( - self.root_url - ): # If an externally hosted image, don't convert to absolute path - return input_data - return str(utils.abspath(input_data)) - - -@document("style") -class Video( - Changeable, - Clearable, - Playable, - Uploadable, - IOComponent, - VideoSerializable, -): - """ - Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). - For the video to be playable in the browser it must have a compatible container and codec combination. Allowed - combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects - that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video. - If the conversion fails, the original video is returned. - Preprocessing: passes the uploaded video as a {str} filepath or URL whose extension can be modified by `format`. - Postprocessing: expects a {str} filepath to a video which is displayed, or a {Tuple[str, str]} where the first element is a filepath to a video and the second element is a filepath to a subtitle file. - Examples-format: a {str} filepath to a local file that contains the video, or a {Tuple[str, str]} where the first element is a filepath to a video file and the second element is a filepath to a subtitle file. - Demos: video_identity, video_subtitle - """ - - def __init__( - self, - value: str | tuple[str, str | None] | Callable | None = None, - *, - format: str | None = None, - source: str = "upload", - label: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - mirror_webcam: bool = True, - include_audio: bool | None = None, - **kwargs, - ): - """ - Parameters: - value: A path or URL for the default value that Video component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component. - format: Format of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format. - source: Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - mirror_webcam: If True webcam will be mirrored. Default is True. - include_audio: Whether the component should record/retain the audio track for a video. By default, audio is excluded for webcam videos and included for uploaded videos. - """ - self.format = format - valid_sources = ["upload", "webcam"] - if source not in valid_sources: - raise ValueError( - f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}" - ) - self.source = source - self.mirror_webcam = mirror_webcam - self.include_audio = ( - include_audio if include_audio is not None else source == "upload" - ) - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "source": self.source, - "value": self.value, - "mirror_webcam": self.mirror_webcam, - "include_audio": self.include_audio, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: str - | tuple[str, str | None] - | Literal[_Keywords.NO_VALUE] - | None = _Keywords.NO_VALUE, - source: str | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "source": source, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess( - self, x: tuple[FileData, FileData | None] | FileData | None - ) -> str | None: - """ - Parameters: - x: A tuple of (video file data, subtitle file data) or just video file data. - Returns: - A string file path or URL to the preprocessed video. Subtitle file data is ignored. - """ - if x is None: - return None - elif isinstance(x, dict): - video = x - else: - video = x[0] - - file_name, file_data, is_file = ( - video.get("name"), - video["data"], - video.get("is_file", False), - ) - - if is_file: - assert file_name is not None, "Received file data without a file name." - file_name = Path(self.make_temp_copy_if_needed(file_name)) - else: - assert file_data is not None, "Received empty file data." - file_name = Path(self.base64_to_temp_file_if_needed(file_data, file_name)) - - uploaded_format = file_name.suffix.replace(".", "") - needs_formatting = self.format is not None and uploaded_format != self.format - flip = self.source == "webcam" and self.mirror_webcam - - if needs_formatting or flip: - format = f".{self.format if needs_formatting else uploaded_format}" - output_options = ["-vf", "hflip", "-c:a", "copy"] if flip else [] - output_options += ["-an"] if not self.include_audio else [] - flip_suffix = "_flip" if flip else "" - output_file_name = str( - file_name.with_name(f"{file_name.stem}{flip_suffix}{format}") - ) - if Path(output_file_name).exists(): - return output_file_name - ff = FFmpeg( - inputs={str(file_name): None}, - outputs={output_file_name: output_options}, - ) - ff.run() - return output_file_name - elif not self.include_audio: - output_file_name = str(file_name.with_name(f"muted_{file_name.name}")) - ff = FFmpeg( - inputs={str(file_name): None}, - outputs={output_file_name: ["-an"]}, - ) - ff.run() - return output_file_name - else: - return str(file_name) - - def postprocess( - self, y: str | tuple[str, str | None] | None - ) -> tuple[FileData | None, FileData | None] | None: - """ - Processes a video to ensure that it is in the correct format before - returning it to the front end. - Parameters: - y: video data in either of the following formats: a tuple of (str video filepath, str subtitle filepath), or a string filepath or URL to an video file, or None. - Returns: - a tuple with the two dictionary, reresent to video and (optional) subtitle, which following formats: - - The first dictionary represents the video file and contains the following keys: - - 'name': a file path to a temporary copy of the processed video. - - 'data': None - - 'is_file': True - - The second dictionary represents the subtitle file and contains the following keys: - - 'name': None - - 'data': Base64 encode the processed subtitle data. - - 'is_file': False - - If subtitle is None, returns (video, None). - - If both video and subtitle are None, returns None. - """ - - if y is None or y == [None, None] or y == (None, None): - return None - if isinstance(y, str): - processed_files = (self._format_video(y), None) - elif isinstance(y, (tuple, list)): - assert ( - len(y) == 2 - ), f"Expected lists of length 2 or tuples of length 2. Received: {y}" - video = y[0] - subtitle = y[1] - processed_files = ( - self._format_video(video), - self._format_subtitle(subtitle), - ) - else: - raise Exception(f"Cannot process type as video: {type(y)}") - - return processed_files - - def _format_video(self, video: str | None) -> FileData | None: - """ - Processes a video to ensure that it is in the correct format. - Parameters: - video: video data in either of the following formats: a string filepath or URL to an video file, or None. - Returns: - a dictionary with the following keys: - - - 'name': a file path to a temporary copy of the processed video. - - 'data': None - - 'is_file': True - """ - if video is None: - return None - - returned_format = video.split(".")[-1].lower() - - if self.format is None or returned_format == self.format: - conversion_needed = False - else: - conversion_needed = True - - # For cases where the video is a URL and does not need to be converted to another format, we can just return the URL - if utils.validate_url(video) and not (conversion_needed): - return {"name": video, "data": None, "is_file": True} - - # For cases where the video needs to be converted to another format - if utils.validate_url(video): - video = self.download_temp_copy_if_needed(video) - if ( - processing_utils.ffmpeg_installed() - and not processing_utils.video_is_playable(video) - ): - warnings.warn( - "Video does not have browser-compatible container or codec. Converting to mp4" - ) - video = processing_utils.convert_video_to_playable_mp4(video) - if self.format is not None and returned_format != self.format: - output_file_name = video[0 : video.rindex(".") + 1] + self.format - ff = FFmpeg(inputs={video: None}, outputs={output_file_name: None}) - ff.run() - video = output_file_name - - video = self.make_temp_copy_if_needed(video) - - return { - "name": video, - "data": None, - "is_file": True, - "orig_name": Path(video).name, - } - - def _format_subtitle(self, subtitle: str | None) -> FileData | None: - """ - Convert subtitle format to VTT and process the video to ensure it meets the HTML5 requirements. - Parameters: - subtitle: subtitle path in either of the VTT and SRT format. - Returns: - a dictionary with the following keys: - - 'name': None - - 'data': base64-encoded subtitle data. - - 'is_file': False - """ - - def srt_to_vtt(srt_file_path, vtt_file_path): - """Convert an SRT subtitle file to a VTT subtitle file""" - with open(srt_file_path, encoding="utf-8") as srt_file, open( - vtt_file_path, "w", encoding="utf-8" - ) as vtt_file: - vtt_file.write("WEBVTT\n\n") - for subtitle_block in srt_file.read().strip().split("\n\n"): - subtitle_lines = subtitle_block.split("\n") - subtitle_timing = subtitle_lines[1].replace(",", ".") - subtitle_text = "\n".join(subtitle_lines[2:]) - vtt_file.write(f"{subtitle_timing} --> {subtitle_timing}\n") - vtt_file.write(f"{subtitle_text}\n\n") - - if subtitle is None: - return None - - valid_extensions = (".srt", ".vtt") - - if Path(subtitle).suffix not in valid_extensions: - raise ValueError( - f"Invalid value for parameter `subtitle`: {subtitle}. Please choose a file with one of these extensions: {valid_extensions}" - ) - - # HTML5 only support vtt format - if Path(subtitle).suffix == ".srt": - temp_file = tempfile.NamedTemporaryFile( - delete=False, suffix=".vtt", dir=self.DEFAULT_TEMP_DIR - ) - - srt_to_vtt(subtitle, temp_file.name) - subtitle = temp_file.name - - subtitle_data = client_utils.encode_url_or_file_to_base64(subtitle) - return {"name": None, "data": subtitle_data, "is_file": False} - - def style(self, *, height: int | None = None, width: int | None = None, **kwargs): - """ - This method can be used to change the appearance of the video component. - Parameters: - height: Height of the video. - width: Width of the video. - """ - self._style["height"] = height - self._style["width"] = width - Component.style( - self, - **kwargs, - ) - return self - - -@document("style") -class Audio( - Changeable, - Clearable, - Playable, - Streamable, - Uploadable, - IOComponent, - FileSerializable, - TokenInterpretable, -): - """ - Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output). - Preprocessing: passes the uploaded audio as a {Tuple(int, numpy.array)} corresponding to (sample rate in Hz, audio data as a 16-bit int array whose values range from -32768 to 32767), or as a {str} filepath, depending on `type`. - Postprocessing: expects a {Tuple(int, numpy.array)} corresponding to (sample rate in Hz, audio data as a float or int numpy array) or as a {str} filepath or URL to an audio file, which gets displayed - Examples-format: a {str} filepath to a local file that contains audio. - Demos: main_note, generate_tone, reverse_audio - Guides: real-time-speech-recognition - """ - - def __init__( - self, - value: str | tuple[int, np.ndarray] | Callable | None = None, - *, - source: str = "upload", - type: str = "numpy", - label: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - streaming: bool = False, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - format: Literal["wav", "mp3"] = "wav", - **kwargs, - ): - """ - Parameters: - value: A path, URL, or [sample_rate, numpy array] tuple (sample rate in Hz, audio data as a float or int numpy array) for the default value that Audio component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. - source: Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input. - type: The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will allow users to upload and edit a audio file; if False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - streaming: If set to True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'microphone'. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - format: The file format to save audio files. Either 'wav' or 'mp3'. wav files are lossless but will tend to be larger files. mp3 files tend to be smaller. Default is wav. Applies both when this component is used as an input (when `type` is "format") and when this component is used as an output. - """ - valid_sources = ["upload", "microphone"] - if source not in valid_sources: - raise ValueError( - f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}" - ) - self.source = source - valid_types = ["numpy", "filepath"] - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - self.type = type - self.streaming = streaming - if streaming and source != "microphone": - raise ValueError( - "Audio streaming only available if source is 'microphone'." - ) - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - TokenInterpretable.__init__(self) - self.format = format - - def get_config(self): - return { - "source": self.source, - "value": self.value, - "streaming": self.streaming, - **IOComponent.get_config(self), - } - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": {"is_file": False, "data": media_data.BASE64_AUDIO}, - "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav", - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - source: str | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "source": source, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess( - self, x: dict[str, Any] | None - ) -> tuple[int, np.ndarray] | str | None: - """ - Parameters: - x: dictionary with keys "name", "data", "is_file", "crop_min", "crop_max". - Returns: - audio in requested format - """ - if x is None: - return x - file_name, file_data, is_file = ( - x["name"], - x["data"], - x.get("is_file", False), - ) - crop_min, crop_max = x.get("crop_min", 0), x.get("crop_max", 100) - if is_file: - if utils.validate_url(file_name): - temp_file_path = self.download_temp_copy_if_needed(file_name) - else: - temp_file_path = self.make_temp_copy_if_needed(file_name) - else: - temp_file_path = self.base64_to_temp_file_if_needed(file_data, file_name) - - sample_rate, data = processing_utils.audio_from_file( - temp_file_path, crop_min=crop_min, crop_max=crop_max - ) - - # Need a unique name for the file to avoid re-using the same audio file if - # a user submits the same audio file twice, but with different crop min/max. - temp_file_path = Path(temp_file_path) - output_file_name = str( - temp_file_path.with_name( - f"{temp_file_path.stem}-{crop_min}-{crop_max}{temp_file_path.suffix}" - ) - ) - - if self.type == "numpy": - return sample_rate, data - elif self.type == "filepath": - output_file = str(Path(output_file_name).with_suffix(f".{self.format}")) - processing_utils.audio_to_file( - sample_rate, data, output_file, format=self.format - ) - return output_file - else: - raise ValueError( - "Unknown type: " - + str(self.type) - + ". Please choose from: 'numpy', 'filepath'." - ) - - def set_interpret_parameters(self, segments: int = 8): - """ - Calculates interpretation score of audio subsections by splitting the audio into subsections, then using a "leave one out" method to calculate the score of each subsection by removing the subsection and measuring the delta of the output value. - Parameters: - segments: Number of interpretation segments to split audio into. - """ - self.interpretation_segments = segments - return self - - def tokenize(self, x): - if x.get("is_file"): - sample_rate, data = processing_utils.audio_from_file(x["name"]) - else: - file_name = self.base64_to_temp_file_if_needed(x["data"]) - sample_rate, data = processing_utils.audio_from_file(file_name) - leave_one_out_sets = [] - tokens = [] - masks = [] - duration = data.shape[0] - boundaries = np.linspace(0, duration, self.interpretation_segments + 1).tolist() - boundaries = [round(boundary) for boundary in boundaries] - for index in range(len(boundaries) - 1): - start, stop = boundaries[index], boundaries[index + 1] - masks.append((start, stop)) - - # Handle the leave one outs - leave_one_out_data = np.copy(data) - leave_one_out_data[start:stop] = 0 - file = tempfile.NamedTemporaryFile( - delete=False, suffix=".wav", dir=self.DEFAULT_TEMP_DIR - ) - processing_utils.audio_to_file(sample_rate, leave_one_out_data, file.name) - out_data = client_utils.encode_file_to_base64(file.name) - leave_one_out_sets.append(out_data) - file.close() - Path(file.name).unlink() - - # Handle the tokens - token = np.copy(data) - token[0:start] = 0 - token[stop:] = 0 - file = tempfile.NamedTemporaryFile( - delete=False, suffix=".wav", dir=self.DEFAULT_TEMP_DIR - ) - processing_utils.audio_to_file(sample_rate, token, file.name) - token_data = client_utils.encode_file_to_base64(file.name) - file.close() - Path(file.name).unlink() - - tokens.append(token_data) - tokens = [{"name": "token.wav", "data": token} for token in tokens] - leave_one_out_sets = [ - {"name": "loo.wav", "data": loo_set} for loo_set in leave_one_out_sets - ] - return tokens, leave_one_out_sets, masks - - def get_masked_inputs(self, tokens, binary_mask_matrix): - # create a "zero input" vector and get sample rate - x = tokens[0]["data"] - file_name = self.base64_to_temp_file_if_needed(x) - sample_rate, data = processing_utils.audio_from_file(file_name) - zero_input = np.zeros_like(data, dtype="int16") - # decode all of the tokens - token_data = [] - for token in tokens: - file_name = self.base64_to_temp_file_if_needed(token["data"]) - _, data = processing_utils.audio_from_file(file_name) - token_data.append(data) - # construct the masked version - masked_inputs = [] - for binary_mask_vector in binary_mask_matrix: - masked_input = np.copy(zero_input) - for t, b in zip(token_data, binary_mask_vector): - masked_input = masked_input + t * int(b) - file = tempfile.NamedTemporaryFile(delete=False, dir=self.DEFAULT_TEMP_DIR) - processing_utils.audio_to_file(sample_rate, masked_input, file.name) - masked_data = client_utils.encode_file_to_base64(file.name) - file.close() - Path(file.name).unlink() - masked_inputs.append(masked_data) - return masked_inputs - - def postprocess(self, y: tuple[int, np.ndarray] | str | None) -> str | dict | None: - """ - Parameters: - y: audio data in either of the following formats: a tuple of (sample_rate, data), or a string filepath or URL to an audio file, or None. - Returns: - base64 url data - """ - if y is None: - return None - if isinstance(y, str) and utils.validate_url(y): - return {"name": y, "data": None, "is_file": True} - if isinstance(y, tuple): - sample_rate, data = y - file_path = self.audio_to_temp_file( - data, sample_rate, dir=self.DEFAULT_TEMP_DIR, format=self.format - ) - self.temp_files.add(file_path) - else: - file_path = self.make_temp_copy_if_needed(y) - return {"name": file_path, "data": None, "is_file": True} - - def check_streamable(self): - if self.source != "microphone": - raise ValueError( - "Audio streaming only available if source is 'microphone'." - ) - - def style( - self, - **kwargs, - ): - """ - This method can be used to change the appearance of the audio component. - """ - Component.style( - self, - **kwargs, - ) - return self - - def as_example(self, input_data: str | None) -> str: - return Path(input_data).name if input_data else "" - - -@document("style") -class File( - Changeable, - Selectable, - Clearable, - Uploadable, - IOComponent, - FileSerializable, -): - """ - Creates a file component that allows uploading generic file (when used as an input) and or displaying generic files (output). - Preprocessing: passes the uploaded file as a {tempfile._TemporaryFileWrapper} or {List[tempfile._TemporaryFileWrapper]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`) - Postprocessing: expects function to return a {str} path to a file, or {List[str]} consisting of paths to files. - Examples-format: a {str} path to a local file that populates the component. - Demos: zip_to_json, zip_files - """ - - def __init__( - self, - value: str | list[str] | Callable | None = None, - *, - file_count: str = "single", - file_types: list[str] | None = None, - type: str = "file", - label: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default file to display, given as str file path. If callable, the function will be called whenever the app loads to set the initial value of the component. - file_count: if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". - file_types: List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. - type: Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.file_count = file_count - self.file_types = file_types - if file_types is not None and not isinstance(file_types, list): - raise ValueError( - f"Parameter file_types must be a list. Received {file_types.__class__.__name__}" - ) - valid_types = [ - "file", - "binary", - "bytes", - ] # "bytes" is included for backwards compatibility - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - if type == "bytes": - warnings.warn( - "The `bytes` type is deprecated and may not work as expected. Please use `binary` instead." - ) - if file_count == "directory" and file_types is not None: - warnings.warn( - "The `file_types` parameter is ignored when `file_count` is 'directory'." - ) - self.type = type - self.select: EventListenerMethod - """ - Event listener for when the user selects file from list. - Uses event data gradio.SelectData to carry `value` referring to name of selected file, and `index` to refer to index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "file_count": self.file_count, - "file_types": self.file_types, - "value": self.value, - "selectable": self.selectable, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess( - self, x: list[dict[str, Any]] | None - ) -> ( - bytes - | tempfile._TemporaryFileWrapper - | list[bytes | tempfile._TemporaryFileWrapper] - | None - ): - """ - Parameters: - x: List of JSON objects with filename as 'name' property and base64 data as 'data' property - Returns: - File objects in requested format - """ - if x is None: - return None - - def process_single_file(f) -> bytes | tempfile._TemporaryFileWrapper: - file_name, data, is_file = ( - f["name"], - f["data"], - f.get("is_file", False), - ) - if self.type == "file": - if is_file: - path = self.make_temp_copy_if_needed(file_name) - else: - data, _ = client_utils.decode_base64_to_binary(data) - path = self.file_bytes_to_file( - data, dir=self.DEFAULT_TEMP_DIR, file_name=file_name - ) - path = str(utils.abspath(path)) - self.temp_files.add(path) - - # Creation of tempfiles here - file = tempfile.NamedTemporaryFile( - delete=False, dir=self.DEFAULT_TEMP_DIR - ) - file.name = path - file.orig_name = file_name # type: ignore - return file - elif ( - self.type == "binary" or self.type == "bytes" - ): # "bytes" is included for backwards compatibility - if is_file: - with open(file_name, "rb") as file_data: - return file_data.read() - return client_utils.decode_base64_to_binary(data)[0] - else: - raise ValueError( - "Unknown type: " - + str(self.type) - + ". Please choose from: 'file', 'bytes'." - ) - - if self.file_count == "single": - if isinstance(x, list): - return process_single_file(x[0]) - else: - return process_single_file(x) - else: - if isinstance(x, list): - return [process_single_file(f) for f in x] - else: - return process_single_file(x) - - def postprocess( - self, y: str | list[str] | None - ) -> dict[str, Any] | list[dict[str, Any]] | None: - """ - Parameters: - y: file path - Returns: - JSON object with key 'name' for filename, 'data' for base64 url, and 'size' for filesize in bytes - """ - if y is None: - return None - if isinstance(y, list): - return [ - { - "orig_name": Path(file).name, - "name": self.make_temp_copy_if_needed(file), - "size": Path(file).stat().st_size, - "data": None, - "is_file": True, - } - for file in y - ] - else: - d = { - "orig_name": Path(y).name, - "name": self.make_temp_copy_if_needed(y), - "size": Path(y).stat().st_size, - "data": None, - "is_file": True, - } - return d - - def style( - self, - **kwargs, - ): - """ - This method can be used to change the appearance of the file component. - """ - Component.style( - self, - **kwargs, - ) - return self - - def as_example(self, input_data: str | list | None) -> str: - if input_data is None: - return "" - elif isinstance(input_data, list): - return ", ".join([Path(file).name for file in input_data]) - else: - return Path(input_data).name - - def api_info(self) -> dict[str, dict | bool]: - if self.file_count == "single": - return self._single_file_api_info() - else: - return self._multiple_file_api_info() - - def serialized_info(self): - if self.file_count == "single": - return self._single_file_serialized_info() - else: - return self._multiple_file_serialized_info() - - def example_inputs(self) -> dict[str, Any]: - if self.file_count == "single": - return self._single_file_example_inputs() - else: - return self._multiple_file_example_inputs() - - -@document("style") -class Dataframe(Changeable, Inputable, Selectable, IOComponent, JSONSerializable): - """ - Accepts or displays 2D input through a spreadsheet-like component for dataframes. - Preprocessing: passes the uploaded spreadsheet data as a {pandas.DataFrame}, {numpy.array}, {List[List]}, or {List} depending on `type` - Postprocessing: expects a {pandas.DataFrame}, {numpy.array}, {List[List]}, {List}, a {Dict} with keys `data` (and optionally `headers`), or {str} path to a csv, which is rendered in the spreadsheet. - Examples-format: a {str} filepath to a csv with data, a pandas dataframe, or a list of lists (excluding headers) where each sublist is a row of data. - Demos: filter_records, matrix_transpose, tax_calculator - """ - - markdown_parser = None - - def __init__( - self, - value: list[list[Any]] | Callable | None = None, - *, - headers: list[str] | None = None, - row_count: int | tuple[int, str] = (1, "dynamic"), - col_count: int | tuple[int, str] | None = None, - datatype: str | list[str] = "str", - type: str = "pandas", - max_rows: int | None = 20, - max_cols: int | None = None, - overflow_row_behaviour: str = "paginate", - label: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - wrap: bool = False, - **kwargs, - ): - """ - Parameters: - value: Default value as a 2-dimensional list of values. If callable, the function will be called whenever the app loads to set the initial value of the component. - headers: List of str header names. If None, no headers are shown. - row_count: Limit number of rows for input and decide whether user can create new rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic' - col_count: Limit number of columns for input and decide whether user can create new columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic' - datatype: Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown". - type: Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array. - label: component name in interface. - max_rows: Maximum number of rows to display at once. Set to None for infinite. - max_cols: Maximum number of columns to display at once. Set to None for infinite. - overflow_row_behaviour: If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - wrap: if True text in table cells will wrap when appropriate, if False the table will scroll horizontally. Defaults to False. - """ - - self.wrap = wrap - self.row_count = self.__process_counts(row_count) - self.col_count = self.__process_counts( - col_count, len(headers) if headers else 3 - ) - - self.__validate_headers(headers, self.col_count[0]) - - self.headers = ( - headers if headers is not None else list(range(1, self.col_count[0] + 1)) - ) - self.datatype = ( - datatype if isinstance(datatype, list) else [datatype] * self.col_count[0] - ) - valid_types = ["pandas", "numpy", "array"] - if type not in valid_types: - raise ValueError( - f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" - ) - self.type = type - values = { - "str": "", - "number": 0, - "bool": False, - "date": "01/01/1970", - "markdown": "", - "html": "", - } - column_dtypes = ( - [datatype] * self.col_count[0] if isinstance(datatype, str) else datatype - ) - self.empty_input = [ - [values[c] for c in column_dtypes] for _ in range(self.row_count[0]) - ] - - self.max_rows = max_rows - self.max_cols = max_cols - self.overflow_row_behaviour = overflow_row_behaviour - self.select: EventListenerMethod - """ - Event listener for when the user selects cell within Dataframe. - Uses event data gradio.SelectData to carry `value` referring to value of selected cell, and `index` tuple to refer to index row and column. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "headers": self.headers, - "datatype": self.datatype, - "row_count": self.row_count, - "col_count": self.col_count, - "value": self.value, - "max_rows": self.max_rows, - "max_cols": self.max_cols, - "overflow_row_behaviour": self.overflow_row_behaviour, - "wrap": self.wrap, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - max_rows: int | None = None, - max_cols: str | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "max_rows": max_rows, - "max_cols": max_cols, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess(self, x: DataframeData): - """ - Parameters: - x: 2D array of str, numeric, or bool data - Returns: - Dataframe in requested format - """ - if self.type == "pandas": - if x.get("headers") is not None: - return pd.DataFrame(x["data"], columns=x.get("headers")) - else: - return pd.DataFrame(x["data"]) - if self.type == "numpy": - return np.array(x["data"]) - elif self.type == "array": - return x["data"] - else: - raise ValueError( - "Unknown type: " - + str(self.type) - + ". Please choose from: 'pandas', 'numpy', 'array'." - ) - - def postprocess( - self, y: str | pd.DataFrame | np.ndarray | list[list[str | float]] | dict - ) -> dict: - """ - Parameters: - y: dataframe in given format - Returns: - JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data - """ - if y is None: - return self.postprocess(self.empty_input) - if isinstance(y, dict): - return y - if isinstance(y, str): - dataframe = pd.read_csv(y) - return { - "headers": list(dataframe.columns), - "data": Dataframe.__process_markdown( - dataframe.to_dict(orient="split")["data"], self.datatype - ), - } - if isinstance(y, pd.DataFrame): - return { - "headers": list(y.columns), # type: ignore - "data": Dataframe.__process_markdown( - y.to_dict(orient="split")["data"], self.datatype # type: ignore - ), - } - if isinstance(y, (np.ndarray, list)): - if len(y) == 0: - return self.postprocess([[]]) - if isinstance(y, np.ndarray): - y = y.tolist() - assert isinstance(y, list), "output cannot be converted to list" - - _headers = self.headers - - if len(self.headers) < len(y[0]): - _headers = [ - *self.headers, - *list(range(len(self.headers) + 1, len(y[0]) + 1)), - ] - elif len(self.headers) > len(y[0]): - _headers = self.headers[: len(y[0])] - - return { - "headers": _headers, - "data": Dataframe.__process_markdown(y, self.datatype), - } - raise ValueError("Cannot process value as a Dataframe") - - @staticmethod - def __process_counts(count, default=3) -> tuple[int, str]: - if count is None: - return (default, "dynamic") - if type(count) == int or type(count) == float: - return (int(count), "dynamic") - else: - return count - - @staticmethod - def __validate_headers(headers: list[str] | None, col_count: int): - if headers is not None and len(headers) != col_count: - raise ValueError( - f"The length of the headers list must be equal to the col_count int.\n" - f"The column count is set to {col_count} but `headers` has {len(headers)} items. " - f"Check the values passed to `col_count` and `headers`." - ) - - @classmethod - def __process_markdown(cls, data: list[list[Any]], datatype: list[str]): - if "markdown" not in datatype: - return data - - if cls.markdown_parser is None: - cls.markdown_parser = utils.get_markdown_parser() - - for i in range(len(data)): - for j in range(len(data[i])): - if datatype[j] == "markdown": - data[i][j] = cls.markdown_parser.render(data[i][j]) - - return data - - def style( - self, - **kwargs, - ): - """ - This method can be used to change the appearance of the DataFrame component. - """ - Component.style( - self, - **kwargs, - ) - return self - - def as_example(self, input_data: pd.DataFrame | np.ndarray | str | None): - if input_data is None: - return "" - elif isinstance(input_data, pd.DataFrame): - return input_data.head(n=5).to_dict(orient="split")["data"] # type: ignore - elif isinstance(input_data, np.ndarray): - return input_data.tolist() - return input_data - - -@document("style") -class Timeseries(Changeable, IOComponent, JSONSerializable): - """ - Creates a component that can be used to upload/preview timeseries csv files or display a dataframe consisting of a time series graphically. - Preprocessing: passes the uploaded timeseries data as a {pandas.DataFrame} into the function - Postprocessing: expects a {pandas.DataFrame} or {str} path to a csv to be returned, which is then displayed as a timeseries graph - Examples-format: a {str} filepath of csv data with time series data. - Demos: fraud_detector - """ - - def __init__( - self, - value: str | Callable | None = None, - *, - x: str | None = None, - y: str | list[str] | None = None, - colors: list[str] | None = None, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: File path for the timeseries csv file. If callable, the function will be called whenever the app loads to set the initial value of the component. - x: Column name of x (time) series. None if csv has no headers, in which case first column is x series. - y: Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - colors: an ordered list of colors to use for each line plot - show_label: if True, will display label. - interactive: if True, will allow users to upload a timeseries csv; if False, can only be used to display timeseries data. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.x = x - if isinstance(y, str): - y = [y] - self.y = y - self.colors = colors - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "x": self.x, - "y": self.y, - "value": self.value, - "colors": self.colors, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - colors: list[str] | None = None, - label: str | None = None, - show_label: bool | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "colors": colors, - "label": label, - "show_label": show_label, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess(self, x: dict | None) -> pd.DataFrame | None: - """ - Parameters: - x: Dict with keys 'data': 2D array of str, numeric, or bool data, 'headers': list of strings for header names, 'range': optional two element list designating start of end of subrange. - Returns: - Dataframe of timeseries data - """ - if x is None: - return x - elif x.get("is_file"): - dataframe = pd.read_csv(x["name"]) - else: - dataframe = pd.DataFrame(data=x["data"], columns=x["headers"]) - if x.get("range") is not None: - dataframe = dataframe.loc[dataframe[self.x or 0] >= x["range"][0]] - dataframe = dataframe.loc[dataframe[self.x or 0] <= x["range"][1]] - return dataframe - - def postprocess(self, y: str | pd.DataFrame | None) -> dict | None: - """ - Parameters: - y: csv or dataframe with timeseries data - Returns: - JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data - """ - if y is None: - return None - if isinstance(y, str): - dataframe = pd.read_csv(y) - return { - "headers": dataframe.columns.values.tolist(), - "data": dataframe.values.tolist(), - } - if isinstance(y, pd.DataFrame): - return {"headers": y.columns.values.tolist(), "data": y.values.tolist()} - raise ValueError("Cannot process value as Timeseries data") - - def style( - self, - **kwargs, - ): - """ - This method can be used to change the appearance of the TimeSeries component. - """ - Component.style( - self, - **kwargs, - ) - return self - - def as_example(self, input_data: str | None) -> str: - return Path(input_data).name if input_data else "" - - -@document() -class State(IOComponent, SimpleSerializable): - """ - Special hidden component that stores session state across runs of the demo by the - same user. The value of the State variable is cleared when the user refreshes the page. - - Preprocessing: No preprocessing is performed - Postprocessing: No postprocessing is performed - Demos: blocks_simple_squares - Guides: real-time-speech-recognition - """ - - allow_string_shortcut = False - - def __init__( - self, - value: Any = None, - **kwargs, - ): - """ - Parameters: - value: the initial value (of arbitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state. - """ - self.stateful = True - IOComponent.__init__(self, value=deepcopy(value), **kwargs) - - -class Variable(State): - """Variable was renamed to State. This class is kept for backwards compatibility.""" - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def get_block_name(self): - return "state" - - -@document("style") -class Button(Clickable, IOComponent, StringSerializable): - """ - Used to create a button, that can be assigned arbitrary click() events. The label (value) of the button can be used as an input or set via the output of a function. - - Preprocessing: passes the button value as a {str} into the function - Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button - Demos: blocks_inputs, blocks_kinematics - """ - - def __init__( - self, - value: str | Callable = "Run", - *, - variant: str = "secondary", - visible: bool = True, - interactive: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default text for the button to display. If callable, the function will be called whenever the app loads to set the initial value of the component. - variant: 'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button. - visible: If False, component will be hidden. - interactive: If False, the Button will be in a disabled state. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - IOComponent.__init__( - self, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - interactive=interactive, - **kwargs, - ) - if variant == "plain": - warnings.warn("'plain' variant deprecated, using 'secondary' instead.") - variant = "secondary" - self.variant = variant - - def get_config(self): - return { - "value": self.value, - "variant": self.variant, - "interactive": self.interactive, - **Component.get_config(self), - } - - @staticmethod - def update( - value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - variant: str | None = None, - visible: bool | None = None, - interactive: bool | None = None, - ): - return { - "variant": variant, - "visible": visible, - "value": value, - "interactive": interactive, - "__type__": "update", - } - - def style( - self, - *, - full_width: bool | None = None, - size: Literal["sm"] | Literal["lg"] | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the button component. - Parameters: - full_width: If True, will expand to fill parent container. - size: Size of the button. Can be "sm" or "lg". - """ - if full_width is not None: - self._style["full_width"] = full_width - if size is not None: - self._style["size"] = size - - Component.style(self, **kwargs) - return self - - -@document("style") -class UploadButton(Clickable, Uploadable, IOComponent, FileSerializable): - """ - Used to create an upload button, when cicked allows a user to upload files that satisfy the specified file type or generic files (if file_type not set). - Preprocessing: passes the uploaded file as a {file-object} or {List[file-object]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`) - Postprocessing: expects function to return a {str} path to a file, or {List[str]} consisting of paths to files. - Examples-format: a {str} path to a local file that populates the component. - Demos: upload_button - """ - - def __init__( - self, - label: str = "Upload a File", - value: str | list[str] | Callable | None = None, - *, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - type: str = "file", - file_count: str = "single", - file_types: list[str] | None = None, - **kwargs, - ): - """ - Parameters: - value: Default text for the button to display. - type: Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object. - file_count: if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". - file_types: List of type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. - label: Text to display on the button. Defaults to "Upload a File". - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.type = type - self.file_count = file_count - if file_count == "directory" and file_types is not None: - warnings.warn( - "The `file_types` parameter is ignored when `file_count` is 'directory'." - ) - if file_types is not None and not isinstance(file_types, list): - raise ValueError( - f"Parameter file_types must be a list. Received {file_types.__class__.__name__}" - ) - self.file_types = file_types - self.label = label - IOComponent.__init__( - self, - label=label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "label": self.label, - "value": self.value, - "file_count": self.file_count, - "file_types": self.file_types, - **Component.get_config(self), - } - - @staticmethod - def update( - value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def preprocess( - self, x: list[dict[str, Any]] | None - ) -> ( - bytes - | tempfile._TemporaryFileWrapper - | list[bytes | tempfile._TemporaryFileWrapper] - | None - ): - """ - Parameters: - x: List of JSON objects with filename as 'name' property and base64 data as 'data' property - Returns: - File objects in requested format - """ - if x is None: - return None - - def process_single_file(f) -> bytes | tempfile._TemporaryFileWrapper: - file_name, data, is_file = ( - f["name"], - f["data"], - f.get("is_file", False), - ) - if self.type == "file": - if is_file: - path = self.make_temp_copy_if_needed(file_name) - else: - data, _ = client_utils.decode_base64_to_binary(data) - path = self.file_bytes_to_file( - data, dir=self.DEFAULT_TEMP_DIR, file_name=file_name - ) - path = str(utils.abspath(path)) - self.temp_files.add(path) - file = tempfile.NamedTemporaryFile( - delete=False, dir=self.DEFAULT_TEMP_DIR - ) - file.name = path - file.orig_name = file_name # type: ignore - return file - elif self.type == "bytes": - if is_file: - with open(file_name, "rb") as file_data: - return file_data.read() - return client_utils.decode_base64_to_binary(data)[0] - else: - raise ValueError( - "Unknown type: " - + str(self.type) - + ". Please choose from: 'file', 'bytes'." - ) - - if self.file_count == "single": - if isinstance(x, list): - return process_single_file(x[0]) - else: - return process_single_file(x) - else: - if isinstance(x, list): - return [process_single_file(f) for f in x] - else: - return process_single_file(x) - - def style( - self, - *, - full_width: bool | None = None, - size: Literal["sm"] | Literal["lg"] | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the button component. - Parameters: - full_width: If True, will expand to fill parent container. - size: Size of the button. Can be "sm" or "lg". - """ - if full_width is not None: - self._style["full_width"] = full_width - if size is not None: - self._style["size"] = size - - Component.style(self, **kwargs) - return self - - -@document("style") -class ColorPicker( - Changeable, Inputable, Submittable, Blurrable, IOComponent, StringSerializable -): - """ - Creates a color picker for user to select a color as string input. - Preprocessing: passes selected color value as a {str} into the function. - Postprocessing: expects a {str} returned from function and sets color picker value to it. - Examples-format: a {str} with a hexadecimal representation of a color, e.g. "#ff0000" for red. - Demos: color_picker, color_generator - """ - - def __init__( - self, - value: str | Callable | None = None, - *, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool = True, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: default text to provide in color picker. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - interactive: if True, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.cleared_value = "#000000" - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": "#000000", - "serialized": "#000000", - } - - def get_config(self): - return { - "value": self.value, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - interactive: bool | None = None, - ): - return { - "value": value, - "label": label, - "show_label": show_label, - "visible": visible, - "interactive": interactive, - "__type__": "update", - } - - def preprocess(self, x: str | None) -> str | None: - """ - Any preprocessing needed to be performed on function input. - Parameters: - x: text - Returns: - text - """ - if x is None: - return None - else: - return str(x) - - def postprocess(self, y: str | None) -> str | None: - """ - Any postprocessing needed to be performed on function output. - Parameters: - y: text - Returns: - text - """ - if y is None: - return None - else: - return str(y) - - -############################ -# Only Output Components -############################ - - -@document("style") -class Label(Changeable, Selectable, IOComponent, JSONSerializable): - """ - Displays a classification label, along with confidence scores of top categories, if provided. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a {Dict[str, float]} of classes and confidences, or {str} with just the class or an {int}/{float} for regression outputs, or a {str} path to a .json file containing a json dictionary in the structure produced by Label.postprocess(). - - Demos: main_note, titanic_survival - Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary-app - """ - - CONFIDENCES_KEY = "confidences" - - def __init__( - self, - value: dict[str, float] | str | float | Callable | None = None, - *, - num_top_classes: int | None = None, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - color: str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If callable, the function will be called whenever the app loads to set the initial value of the component. - num_top_classes: number of most confident classes to show. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - color: The background color of the label (either a valid css color name or hexadecimal string). - """ - self.num_top_classes = num_top_classes - self.color = color - self.select: EventListenerMethod - """ - Event listener for when the user selects a category from Label. - Uses event data gradio.SelectData to carry `value` referring to name of selected category, and `index` to refer to index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "num_top_classes": self.num_top_classes, - "value": self.value, - "color": self.color, - "selectable": self.selectable, - **IOComponent.get_config(self), - } - - def postprocess(self, y: dict[str, float] | str | float | None) -> dict | None: - """ - Parameters: - y: a dictionary mapping labels to confidence value, or just a string/numerical label by itself - Returns: - Object with key 'label' representing primary label, and key 'confidences' representing a list of label-confidence pairs - """ - if y is None or y == {}: - return None - if isinstance(y, str) and y.endswith(".json") and Path(y).exists(): - return self.serialize(y) - if isinstance(y, (str, float, int)): - return {"label": str(y)} - if isinstance(y, dict): - if "confidences" in y and isinstance(y["confidences"], dict): - y = y["confidences"] - y = {c["label"]: c["confidence"] for c in y} - sorted_pred = sorted(y.items(), key=operator.itemgetter(1), reverse=True) - if self.num_top_classes is not None: - sorted_pred = sorted_pred[: self.num_top_classes] - return { - "label": sorted_pred[0][0], - "confidences": [ - {"label": pred[0], "confidence": pred[1]} for pred in sorted_pred - ], - } - raise ValueError( - "The `Label` output interface expects one of: a string label, or an int label, a " - "float label, or a dictionary whose keys are labels and values are confidences. " - f"Instead, got a {type(y)}" - ) - - @staticmethod - def update( - value: dict[str, float] - | str - | float - | Literal[_Keywords.NO_VALUE] - | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - color: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - ): - # If color is not specified (NO_VALUE) map it to None so that - # it gets filtered out in postprocess. This will mean the color - # will not be updated in the front-end - if color is _Keywords.NO_VALUE: - color = None - # If the color was specified by the developer as None - # Map is so that the color is updated to be transparent, - # e.g. no background default state. - elif color is None: - color = "transparent" - return { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "color": color, - "__type__": "update", - } - - def style( - self, - *, - container: bool | None = None, - ): - """ - This method can be used to change the appearance of the label component. - Parameters: - container: If True, will add a container to the label - providing some extra padding around the border. - """ - Component.style(self, container=container) - return self - - -@document("style") -class HighlightedText(Changeable, Selectable, IOComponent, JSONSerializable): - """ - Displays text that contains spans that are highlighted by category or numerical value. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a {List[Tuple[str, float | str]]]} consisting of spans of text and their associated labels, or a {Dict} with two keys: (1) "text" whose value is the complete text, and "entities", which is a list of dictionaries, each of which have the keys: "entity" (consisting of the entity label), "start" (the character index where the label starts), and "end" (the character index where the label ends). Entities should not overlap. - - Demos: diff_texts, text_analysis - Guides: named-entity-recognition - """ - - def __init__( - self, - value: list[tuple[str, str | float | None]] | dict | Callable | None = None, - *, - color_map: dict[str, str] - | None = None, # Parameter moved to HighlightedText.style() - show_legend: bool = False, - combine_adjacent: bool = False, - adjacent_separator: str = "", - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default value to show. If callable, the function will be called whenever the app loads to set the initial value of the component. - show_legend: whether to show span categories in a separate legend or inline. - combine_adjacent: If True, will merge the labels of adjacent tokens belonging to the same category. - adjacent_separator: Specifies the separator to be used between tokens if combine_adjacent is True. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.color_map = color_map - if color_map is not None: - warnings.warn( - "The 'color_map' parameter has been moved from the constructor to `HighlightedText.style()` ", - ) - self.show_legend = show_legend - self.combine_adjacent = combine_adjacent - self.adjacent_separator = adjacent_separator - self.select: EventListenerMethod - """ - Event listener for when the user selects Highlighted text span. - Uses event data gradio.SelectData to carry `value` referring to selected [text, label] tuple, and `index` to refer to span index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "color_map": self.color_map, - "show_legend": self.show_legend, - "value": self.value, - "selectable": self.selectable, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: list[tuple[str, str | float | None]] - | dict - | Literal[_Keywords.NO_VALUE] - | None = _Keywords.NO_VALUE, - color_map: dict[str, str] | None = None, - show_legend: bool | None = None, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "color_map": color_map, - "show_legend": show_legend, - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def postprocess( - self, y: list[tuple[str, str | float | None]] | dict | None - ) -> list[tuple[str, str | float | None]] | None: - """ - Parameters: - y: List of (word, category) tuples - Returns: - List of (word, category) tuples - """ - if y is None: - return None - if isinstance(y, dict): - try: - text = y["text"] - entities = y["entities"] - except KeyError as ke: - raise ValueError( - "Expected a dictionary with keys 'text' and 'entities' " - "for the value of the HighlightedText component." - ) from ke - if len(entities) == 0: - y = [(text, None)] - else: - list_format = [] - index = 0 - entities = sorted(entities, key=lambda x: x["start"]) - for entity in entities: - list_format.append((text[index : entity["start"]], None)) - list_format.append( - (text[entity["start"] : entity["end"]], entity["entity"]) - ) - index = entity["end"] - list_format.append((text[index:], None)) - y = list_format - if self.combine_adjacent: - output = [] - running_text, running_category = None, None - for text, category in y: - if running_text is None: - running_text = text - running_category = category - elif category == running_category: - running_text += self.adjacent_separator + text - elif not text: - # Skip fully empty item, these get added in processing - # of dictionaries. - pass - else: - output.append((running_text, running_category)) - running_text = text - running_category = category - if running_text is not None: - output.append((running_text, running_category)) - return output - else: - return y - - def style( - self, - *, - color_map: dict[str, str] | None = None, - container: bool | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the HighlightedText component. - Parameters: - color_map: Map between category and respective colors. - container: If True, will place the component in a container - providing some extra padding around the border. - """ - if color_map is not None: - self._style["color_map"] = color_map - - Component.style(self, container=container, **kwargs) - return self - - -@document("style") -class AnnotatedImage(Selectable, IOComponent, JSONSerializable): - """ - Displays a base image and colored subsections on top of that image. Subsections can take the from of rectangles (e.g. object detection) or masks (e.g. image segmentation). - Preprocessing: this component does *not* accept input. - Postprocessing: expects a {Tuple[numpy.ndarray | PIL.Image | str, List[Tuple[numpy.ndarray | Tuple[int, int, int, int], str]]]} consisting of a base image and a list of subsections, that are either (x1, y1, x2, y2) tuples identifying object boundaries, or 0-1 confidence masks of the same shape as the image. A label is provided for each subsection. - - Demos: image_segmentation - """ - - def __init__( - self, - value: tuple[ - np.ndarray | _Image.Image | str, - list[tuple[np.ndarray | tuple[int, int, int, int], str]], - ] - | None = None, - *, - show_legend: bool = True, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Tuple of base image and list of (subsection, label) pairs. - show_legend: If True, will show a legend of the subsections. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.show_legend = show_legend - self.select: EventListenerMethod - """ - Event listener for when the user selects Image subsection. - Uses event data gradio.SelectData to carry `value` referring to selected subsection label, and `index` to refer to subsection index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "show_legend": self.show_legend, - "value": self.value, - "selectable": self.selectable, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: tuple[ - np.ndarray | _Image.Image | str, - list[tuple[np.ndarray | tuple[int, int, int, int], str]], - ] - | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE, - show_legend: bool | None = None, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "show_legend": show_legend, - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def postprocess( - self, - y: tuple[ - np.ndarray | _Image.Image | str, - list[tuple[np.ndarray | tuple[int, int, int, int], str]], - ], - ) -> tuple[dict, list[tuple[dict, str]]] | None: - """ - Parameters: - y: Tuple of base image and list of subsections, with each subsection a two-part tuple where the first element is a 4 element bounding box or a 0-1 confidence mask, and the second element is the label. - Returns: - Tuple of base image file and list of subsections, with each subsection a two-part tuple where the first element image path of the mask, and the second element is the label. - """ - if y is None: - return None - base_img = y[0] - if isinstance(base_img, str): - base_img_path = base_img - base_img = np.array(_Image.open(base_img)) - elif isinstance(base_img, np.ndarray): - base_file = self.img_array_to_temp_file(base_img, dir=self.DEFAULT_TEMP_DIR) - base_img_path = str(utils.abspath(base_file)) - elif isinstance(base_img, _Image.Image): - base_file = self.pil_to_temp_file(base_img, dir=self.DEFAULT_TEMP_DIR) - base_img_path = str(utils.abspath(base_file)) - base_img = np.array(base_img) - else: - raise ValueError( - "AnnotatedImage only accepts filepaths, PIL images or numpy arrays for the base image." - ) - self.temp_files.add(base_img_path) - - sections = [] - color_map = self._style.get("color_map", {}) - - def hex_to_rgb(value): - value = value.lstrip("#") - lv = len(value) - return [int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3)] - - for mask, label in y[1]: - mask_array = np.zeros((base_img.shape[0], base_img.shape[1])) - if isinstance(mask, np.ndarray): - mask_array = mask - else: - x1, y1, x2, y2 = mask - border_width = 3 - mask_array[y1:y2, x1:x2] = 0.5 - mask_array[y1:y2, x1 : x1 + border_width] = 1 - mask_array[y1:y2, x2 - border_width : x2] = 1 - mask_array[y1 : y1 + border_width, x1:x2] = 1 - mask_array[y2 - border_width : y2, x1:x2] = 1 - - if label in color_map: - rgb_color = hex_to_rgb(color_map[label]) - else: - rgb_color = [255, 0, 0] - colored_mask = np.zeros((base_img.shape[0], base_img.shape[1], 4)) - solid_mask = np.copy(mask_array) - solid_mask[solid_mask > 0] = 1 - - colored_mask[:, :, 0] = rgb_color[0] * solid_mask - colored_mask[:, :, 1] = rgb_color[1] * solid_mask - colored_mask[:, :, 2] = rgb_color[2] * solid_mask - colored_mask[:, :, 3] = mask_array * 255 - - colored_mask_img = _Image.fromarray((colored_mask).astype(np.uint8)) - - mask_file = self.pil_to_temp_file( - colored_mask_img, dir=self.DEFAULT_TEMP_DIR - ) - mask_file_path = str(utils.abspath(mask_file)) - self.temp_files.add(mask_file_path) - - sections.append( - ({"name": mask_file_path, "data": None, "is_file": True}, label) - ) - - return {"name": base_img_path, "data": None, "is_file": True}, sections - - def style( - self, - *, - height: int | None = None, - width: int | None = None, - color_map: dict[str, str] | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the Image component. - Parameters: - height: Height of the image. - width: Width of the image. - color_map: A dictionary mapping labels to colors. The colors must be specified as hex codes. - """ - self._style["height"] = height - self._style["width"] = width - self._style["color_map"] = color_map - Component.style( - self, - **kwargs, - ) - return self - - -@document("style") -class JSON(Changeable, IOComponent, JSONSerializable): - """ - Used to display arbitrary JSON output prettily. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a {str} filepath to a file containing valid JSON -- or a {list} or {dict} that is valid JSON - - Demos: zip_to_json, blocks_xray - """ - - def __init__( - self, - value: str | dict | list | Callable | None = None, - *, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default value. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "value": self.value, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def postprocess(self, y: dict | list | str | None) -> dict | list | None: - """ - Parameters: - y: either a string filepath to a JSON file, or a Python list or dict that can be converted to JSON - Returns: - JSON output in Python list or dict format - """ - if y is None: - return None - if isinstance(y, str): - return json.loads(y) - else: - return y - - def style(self, *, container: bool | None = None, **kwargs): - """ - This method can be used to change the appearance of the JSON component. - Parameters: - container: If True, will place the JSON in a container - providing some extra padding around the border. - """ - Component.style(self, container=container, **kwargs) - return self - - -@document() -class HTML(Changeable, IOComponent, StringSerializable): - """ - Used to display arbitrary HTML output. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a valid HTML {str}. - - Demos: text_analysis - Guides: key-features - """ - - def __init__( - self, - value: str | Callable = "", - *, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default value. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "value": self.value, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def style(self): - return self - - -@document("style") -class Gallery(IOComponent, GallerySerializable, Selectable): - """ - Used to display a list of images as a gallery that can be scrolled through. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a list of images in any format, {List[numpy.array | PIL.Image | str]}, or a {List} of (image, {str} caption) tuples and displays them. - - Demos: fake_gan - """ - - def __init__( - self, - value: list[np.ndarray | _Image.Image | str | tuple] | Callable | None = None, - *, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: List of images to display in the gallery by default. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.select: EventListenerMethod - """ - Event listener for when the user selects image within Gallery. - Uses event data gradio.SelectData to carry `value` referring to caption of selected image, and `index` to refer to index. - See EventData documentation on how to use this event data. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def get_config(self): - return { - "value": self.value, - **IOComponent.get_config(self), - } - - def postprocess( - self, - y: list[np.ndarray | _Image.Image | str] - | list[tuple[np.ndarray | _Image.Image | str, str]] - | None, - ) -> list[str]: - """ - Parameters: - y: list of images, or list of (image, caption) tuples - Returns: - list of string file paths to images in temp directory - """ - if y is None: - return [] - output = [] - for img in y: - caption = None - if isinstance(img, (tuple, list)): - img, caption = img - if isinstance(img, np.ndarray): - file = self.img_array_to_temp_file(img, dir=self.DEFAULT_TEMP_DIR) - file_path = str(utils.abspath(file)) - self.temp_files.add(file_path) - elif isinstance(img, _Image.Image): - file = self.pil_to_temp_file(img, dir=self.DEFAULT_TEMP_DIR) - file_path = str(utils.abspath(file)) - self.temp_files.add(file_path) - elif isinstance(img, str): - if utils.validate_url(img): - file_path = img - else: - file_path = self.make_temp_copy_if_needed(img) - else: - raise ValueError(f"Cannot process type as image: {type(img)}") - - if caption is not None: - output.append( - [{"name": file_path, "data": None, "is_file": True}, caption] - ) - else: - output.append({"name": file_path, "data": None, "is_file": True}) - - return output - - def style( - self, - *, - grid: int | tuple | None = None, - columns: int | tuple | None = None, - rows: int | tuple | None = None, - height: str | None = None, - container: bool | None = None, - preview: bool | None = None, - object_fit: str | None = None, - **kwargs, - ): - """ - This method can be used to change the appearance of the gallery component. - Parameters: - grid: ('grid' has been renamed to 'columns') Represents the number of images that should be shown in one row, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints - columns: Represents the number of columns in the image grid, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints - rows: Represents the number of rows in the image grid, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints - height: Height of the gallery. - container: If True, will place gallery in a container - providing some extra padding around the border. - preview: If True, will display the Gallery in preview mode, which shows all of the images as thumbnails and allows the user to click on them to view them in full size. - object_fit: CSS object-fit property for the thumbnail images in the gallery. Can be "contain", "cover", "fill", "none", or "scale-down". - """ - if grid is not None: - warnings.warn( - "The 'grid' parameter will be deprecated. Please use 'columns' instead.", - ) - self._style["grid_cols"] = grid - if columns is not None: - self._style["grid_cols"] = columns - if rows is not None: - self._style["grid_rows"] = rows - if height is not None: - self._style["height"] = height - if preview is not None: - self._style["preview"] = preview - if object_fit is not None: - self._style["object_fit"] = object_fit - - Component.style(self, container=container, **kwargs) - return self - - -class Carousel(IOComponent, Changeable, SimpleSerializable): - """ - Deprecated Component - """ - - def __init__( - self, - *args, - **kwargs, - ): - raise DeprecationWarning( - "The Carousel component is deprecated. Please consider using the Gallery " - "component, which can be used to display images (and optional captions).", - ) - - -@document("style") -class Chatbot(Changeable, Selectable, IOComponent, JSONSerializable): - """ - Displays a chatbot output showing both user submitted messages and responses. Supports a subset of Markdown including bold, italics, code, and images. - Preprocessing: this component does *not* accept input. - Postprocessing: expects function to return a {List[List[str | None | Tuple]]}, a list of lists. The inner list should have 2 elements: the user message and the response message. Messages should be strings, tuples, or Nones. If the message is a string, it can include Markdown. If it is a tuple, it should consist of (string filepath to image/video/audio, [optional string alt text]). Messages that are `None` are not displayed. - - Demos: chatbot_simple, chatbot_multimodal - Guides: creating-a-chatbot - """ - - def __init__( - self, - value: list[list[str | tuple[str] | tuple[str, str] | None]] - | Callable - | None = None, - color_map: dict[str, str] | None = None, # Parameter moved to Chatbot.style() - *, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default value to show in chatbot. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - if color_map is not None: - warnings.warn( - "The 'color_map' parameter has been deprecated.", - ) - self.select: EventListenerMethod - """ - Event listener for when the user selects message from Chatbot. - Uses event data gradio.SelectData to carry `value` referring to text of selected message, and `index` tuple to refer to [message, participant] index. - See EventData documentation on how to use this event data. - """ - - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "value": self.value, - "selectable": self.selectable, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: list[list[str | tuple[str] | tuple[str, str] | None]] - | Literal[_Keywords.NO_VALUE] - | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def _preprocess_chat_messages( - self, chat_message: str | dict | None - ) -> str | tuple[str] | tuple[str, str] | None: - if chat_message is None: - return None - elif isinstance(chat_message, dict): - if chat_message["alt_text"] is not None: - return (chat_message["name"], chat_message["alt_text"]) - else: - return (chat_message["name"],) - else: # string - return chat_message - - def preprocess( - self, - y: list[list[str | dict | None] | tuple[str | dict | None, str | dict | None]], - ) -> list[list[str | tuple[str] | tuple[str, str] | None]]: - if y is None: - return y - processed_messages = [] - for message_pair in y: - assert isinstance( - message_pair, (tuple, list) - ), f"Expected a list of lists or list of tuples. Received: {message_pair}" - assert ( - len(message_pair) == 2 - ), f"Expected a list of lists of length 2 or list of tuples of length 2. Received: {message_pair}" - processed_messages.append( - [ - self._preprocess_chat_messages(message_pair[0]), - self._preprocess_chat_messages(message_pair[1]), - ] - ) - return processed_messages - - def _postprocess_chat_messages( - self, chat_message: str | tuple | list | None - ) -> str | dict | None: - if chat_message is None: - return None - elif isinstance(chat_message, (tuple, list)): - file_uri = chat_message[0] - if utils.validate_url(file_uri): - filepath = file_uri - else: - filepath = self.make_temp_copy_if_needed(file_uri) - - mime_type = client_utils.get_mimetype(filepath) - return { - "name": filepath, - "mime_type": mime_type, - "alt_text": chat_message[1] if len(chat_message) > 1 else None, - "data": None, # These last two fields are filled in by the frontend - "is_file": True, - } - elif isinstance(chat_message, str): - chat_message = inspect.cleandoc(chat_message) - return chat_message - else: - raise ValueError(f"Invalid message for Chatbot component: {chat_message}") - - def postprocess( - self, - y: list[list[str | tuple[str] | tuple[str, str] | None] | tuple], - ) -> list[list[str | dict | None]]: - """ - Parameters: - y: List of lists representing the message and response pairs. Each message and response should be a string, which may be in Markdown format. It can also be a tuple whose first element is a string filepath or URL to an image/video/audio, and second (optional) element is the alt text, in which case the media file is displayed. It can also be None, in which case that message is not displayed. - Returns: - List of lists representing the message and response. Each message and response will be a string of HTML, or a dictionary with media information. Or None if the message is not to be displayed. - """ - if y is None: - return [] - processed_messages = [] - for message_pair in y: - assert isinstance( - message_pair, (tuple, list) - ), f"Expected a list of lists or list of tuples. Received: {message_pair}" - assert ( - len(message_pair) == 2 - ), f"Expected a list of lists of length 2 or list of tuples of length 2. Received: {message_pair}" - processed_messages.append( - [ - self._postprocess_chat_messages(message_pair[0]), - self._postprocess_chat_messages(message_pair[1]), - ] - ) - return processed_messages - - def style(self, height: int | None = None, **kwargs): - """ - This method can be used to change the appearance of the Chatbot component. - """ - if height is not None: - self._style["height"] = height - if kwargs.get("color_map") is not None: - warnings.warn("The 'color_map' parameter has been deprecated.") - - Component.style( - self, - **kwargs, - ) - return self - - -@document("style") -class Model3D( - Changeable, Uploadable, Editable, Clearable, IOComponent, FileSerializable -): - """ - Component allows users to upload or view 3D Model files (.obj, .glb, or .gltf). - Preprocessing: This component passes the uploaded file as a {str} filepath. - Postprocessing: expects function to return a {str} path to a file of type (.obj, glb, or .gltf) - - Demos: model3D - Guides: how-to-use-3D-model-component - """ - - def __init__( - self, - value: str | Callable | None = None, - *, - clear_color: list[float] | None = None, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: path to (.obj, glb, or .gltf) file to show in model3D viewer. If callable, the function will be called whenever the app loads to set the initial value of the component. - clear_color: background color of scene - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.clear_color = clear_color or [0, 0, 0, 0] - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "clearColor": self.clear_color, - "value": self.value, - **IOComponent.get_config(self), - } - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": {"is_file": False, "data": media_data.BASE64_MODEL3D}, - "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/Box.gltf", - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def preprocess(self, x: dict[str, str] | None) -> str | None: - """ - Parameters: - x: JSON object with filename as 'name' property and base64 data as 'data' property - Returns: - string file path to temporary file with the 3D image model - """ - if x is None: - return x - file_name, file_data, is_file = ( - x["name"], - x["data"], - x.get("is_file", False), - ) - if is_file: - temp_file_path = self.make_temp_copy_if_needed(file_name) - else: - temp_file_path = self.base64_to_temp_file_if_needed(file_data, file_name) - - return temp_file_path - - def postprocess(self, y: str | None) -> dict[str, str] | None: - """ - Parameters: - y: path to the model - Returns: - file name mapped to base64 url data - """ - if y is None: - return y - data = { - "name": self.make_temp_copy_if_needed(y), - "data": None, - "is_file": True, - } - return data - - def style(self, **kwargs): - """ - This method can be used to change the appearance of the Model3D component. - """ - Component.style( - self, - **kwargs, - ) - return self - - def as_example(self, input_data: str | None) -> str: - return Path(input_data).name if input_data else "" - - -@document() -class Plot(Changeable, Clearable, IOComponent, JSONSerializable): - """ - Used to display various kinds of plots (matplotlib, plotly, or bokeh are supported) - Preprocessing: this component does *not* accept input. - Postprocessing: expects either a {matplotlib.figure.Figure}, a {plotly.graph_objects._figure.Figure}, or a {dict} corresponding to a bokeh plot (json_item format) - - Demos: altair_plot, outbreak_forecast, blocks_kinematics, stock_forecast, map_airbnb - Guides: plot-component-for-maps - """ - - def __init__( - self, - value: Callable | None | pd.DataFrame = None, - *, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component. - label: component name in interface. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - IOComponent.__init__( - self, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - try: - import bokeh # type: ignore - - bokeh_version = bokeh.__version__ - except ImportError: - bokeh_version = None - return { - "value": self.value, - "bokeh_version": bokeh_version, - **IOComponent.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def postprocess(self, y) -> dict[str, str] | None: - """ - Parameters: - y: plot data - Returns: - plot type mapped to plot base64 data - """ - import matplotlib.figure - - if y is None: - return None - if isinstance(y, (ModuleType, matplotlib.figure.Figure)): # type: ignore - dtype = "matplotlib" - out_y = processing_utils.encode_plot_to_base64(y) - elif "bokeh" in y.__module__: - dtype = "bokeh" - from bokeh.embed import json_item # type: ignore - - out_y = json.dumps(json_item(y)) - else: - is_altair = "altair" in y.__module__ - dtype = "altair" if is_altair else "plotly" - out_y = y.to_json() - return {"type": dtype, "plot": out_y} - - def style(self, container: bool | None = None): - Component.style( - self, - container=container, - ) - return self - - -class AltairPlot: - @staticmethod - def create_legend(position, title): - if position == "none": - legend = None - else: - position = {"orient": position} if position else {} - legend = {"title": title, **position} - - return legend - - @staticmethod - def create_scale(limit): - return alt.Scale(domain=limit) if limit else alt.Undefined - - -@document() -class ScatterPlot(Plot): - """ - Create a scatter plot. - - Preprocessing: this component does *not* accept input. - Postprocessing: expects a pandas dataframe with the data to plot. - - Demos: native_plots - Guides: creating-a-dashboard-from-bigquery-data - """ - - def __init__( - self, - value: pd.DataFrame | Callable | None = None, - x: str | None = None, - y: str | None = None, - *, - color: str | None = None, - size: str | None = None, - shape: str | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - size_legend_title: str | None = None, - shape_legend_title: str | None = None, - color_legend_position: str | None = None, - size_legend_position: str | None = None, - shape_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - x_lim: list[int | float] | None = None, - y_lim: list[int | float] | None = None, - caption: str | None = None, - interactive: bool | None = True, - label: str | None = None, - every: float | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - ): - """ - Parameters: - value: The pandas dataframe containing the data to display in a scatter plot, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component. - x: Column corresponding to the x axis. - y: Column corresponding to the y axis. - color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. - size: The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size. - shape: The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape. - title: The title to display on top of the chart. - tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. - x_title: The title given to the x axis. By default, uses the value of the x parameter. - y_title: The title given to the y axis. By default, uses the value of the y parameter. - color_legend_title: The title given to the color legend. By default, uses the value of color parameter. - size_legend_title: The title given to the size legend. By default, uses the value of the size parameter. - shape_legend_title: The title given to the shape legend. By default, uses the value of the shape parameter. - color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - size_legend_position: The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - shape_legend_position: The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - height: The height of the plot in pixels. - width: The width of the plot in pixels. - x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. - y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. - caption: The (optional) caption to display below the plot. - interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. - label: The (optional) label to display on the top left corner of the plot. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: Whether the label should be displayed. - visible: Whether the plot should be visible. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.x = x - self.y = y - self.color = color - self.size = size - self.shape = shape - self.tooltip = tooltip - self.title = title - self.x_title = x_title - self.y_title = y_title - self.color_legend_title = color_legend_title - self.color_legend_position = color_legend_position - self.size_legend_title = size_legend_title - self.size_legend_position = size_legend_position - self.shape_legend_title = shape_legend_title - self.shape_legend_position = shape_legend_position - self.caption = caption - self.interactive_chart = interactive - self.width = width - self.height = height - self.x_lim = x_lim - self.y_lim = y_lim - super().__init__( - value=value, - label=label, - every=every, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - ) - - def get_config(self): - config = super().get_config() - config["caption"] = self.caption - return config - - def get_block_name(self) -> str: - return "plot" - - @staticmethod - def update( - value: DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE, - x: str | None = None, - y: str | None = None, - color: str | None = None, - size: str | None = None, - shape: str | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - size_legend_title: str | None = None, - shape_legend_title: str | None = None, - color_legend_position: str | None = None, - size_legend_position: str | None = None, - shape_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - x_lim: list[int | float] | None = None, - y_lim: list[int | float] | None = None, - interactive: bool | None = None, - caption: str | None = None, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - """Update an existing plot component. - - If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified. - - Parameters: - value: The pandas dataframe containing the data to display in a scatter plot. - x: Column corresponding to the x axis. - y: Column corresponding to the y axis. - color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. - size: The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size. - shape: The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape. - title: The title to display on top of the chart. - tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. - x_title: The title given to the x axis. By default, uses the value of the x parameter. - y_title: The title given to the y axis. By default, uses the value of the y parameter. - color_legend_title: The title given to the color legend. By default, uses the value of color parameter. - size_legend_title: The title given to the size legend. By default, uses the value of the size parameter. - shape_legend_title: The title given to the shape legend. By default, uses the value of the shape parameter. - color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - size_legend_position: The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - shape_legend_position: The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - height: The height of the plot in pixels. - width: The width of the plot in pixels. - x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. - y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. - interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. - caption: The (optional) caption to display below the plot. - label: The (optional) label to display in the top left corner of the plot. - show_label: Whether the label should be displayed. - visible: Whether the plot should be visible. - """ - properties = [ - x, - y, - color, - size, - shape, - title, - tooltip, - x_title, - y_title, - color_legend_title, - size_legend_title, - shape_legend_title, - color_legend_position, - size_legend_position, - shape_legend_position, - height, - width, - x_lim, - y_lim, - interactive, - ] - if any(properties): - if not isinstance(value, pd.DataFrame): - raise ValueError( - "In order to update plot properties the value parameter " - "must be provided, and it must be a Dataframe. Please pass a value " - "parameter to gr.ScatterPlot.update." - ) - if x is None or y is None: - raise ValueError( - "In order to update plot properties, the x and y axis data " - "must be specified. Please pass valid values for x an y to " - "gr.ScatterPlot.update." - ) - chart = ScatterPlot.create_plot(value, *properties) - value = {"type": "altair", "plot": chart.to_json(), "chart": "scatter"} - - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "caption": caption, - "__type__": "update", - } - return updated_config - - @staticmethod - def create_plot( - value: pd.DataFrame, - x: str, - y: str, - color: str | None = None, - size: str | None = None, - shape: str | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - size_legend_title: str | None = None, - shape_legend_title: str | None = None, - color_legend_position: str | None = None, - size_legend_position: str | None = None, - shape_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - x_lim: list[int | float] | None = None, - y_lim: list[int | float] | None = None, - interactive: bool | None = True, - ): - """Helper for creating the scatter plot.""" - interactive = True if interactive is None else interactive - encodings = { - "x": alt.X( - x, # type: ignore - title=x_title or x, # type: ignore - scale=AltairPlot.create_scale(x_lim), # type: ignore - ), # ignore: type - "y": alt.Y( - y, # type: ignore - title=y_title or y, # type: ignore - scale=AltairPlot.create_scale(y_lim), # type: ignore - ), - } - properties = {} - if title: - properties["title"] = title - if height: - properties["height"] = height - if width: - properties["width"] = width - if color: - if is_numeric_dtype(value[color]): - domain = [value[color].min(), value[color].max()] - range_ = [0, 1] - type_ = "quantitative" - else: - domain = value[color].unique().tolist() - range_ = list(range(len(domain))) - type_ = "nominal" - - encodings["color"] = { - "field": color, - "type": type_, - "legend": AltairPlot.create_legend( - position=color_legend_position, title=color_legend_title or color - ), - "scale": {"domain": domain, "range": range_}, - } - if tooltip: - encodings["tooltip"] = tooltip - if size: - encodings["size"] = { - "field": size, - "type": "quantitative" if is_numeric_dtype(value[size]) else "nominal", - "legend": AltairPlot.create_legend( - position=size_legend_position, title=size_legend_title or size - ), - } - if shape: - encodings["shape"] = { - "field": shape, - "type": "quantitative" if is_numeric_dtype(value[shape]) else "nominal", - "legend": AltairPlot.create_legend( - position=shape_legend_position, title=shape_legend_title or shape - ), - } - chart = ( - alt.Chart(value) # type: ignore - .mark_point(clip=True) # type: ignore - .encode(**encodings) - .properties(background="transparent", **properties) - ) - if interactive: - chart = chart.interactive() - - return chart - - def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None: - # if None or update - if y is None or isinstance(y, Dict): - return y - if self.x is None or self.y is None: - raise ValueError("No value provided for required parameters `x` and `y`.") - chart = self.create_plot( - value=y, - x=self.x, - y=self.y, - color=self.color, - size=self.size, - shape=self.shape, - title=self.title, - tooltip=self.tooltip, - x_title=self.x_title, - y_title=self.y_title, - color_legend_title=self.color_legend_title, - size_legend_title=self.size_legend_title, - shape_legend_title=self.size_legend_title, - color_legend_position=self.color_legend_position, - size_legend_position=self.size_legend_position, - shape_legend_position=self.shape_legend_position, - interactive=self.interactive_chart, - height=self.height, - width=self.width, - x_lim=self.x_lim, - y_lim=self.y_lim, - ) - - return {"type": "altair", "plot": chart.to_json(), "chart": "scatter"} - - -@document() -class LinePlot(Plot): - """ - Create a line plot. - - Preprocessing: this component does *not* accept input. - Postprocessing: expects a pandas dataframe with the data to plot. - - Demos: native_plots, live_dashboard - """ - - def __init__( - self, - value: pd.DataFrame | Callable | None = None, - x: str | None = None, - y: str | None = None, - *, - color: str | None = None, - stroke_dash: str | None = None, - overlay_point: bool | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - stroke_dash_legend_title: str | None = None, - color_legend_position: str | None = None, - stroke_dash_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - x_lim: list[int] | None = None, - y_lim: list[int] | None = None, - caption: str | None = None, - interactive: bool | None = True, - label: str | None = None, - show_label: bool = True, - every: float | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - ): - """ - Parameters: - value: The pandas dataframe containing the data to display in a scatter plot. - x: Column corresponding to the x axis. - y: Column corresponding to the y axis. - color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. - stroke_dash: The column to determine the symbol used to draw the line, e.g. dashed lines, dashed lines with points. - overlay_point: Whether to draw a point on the line for each (x, y) coordinate pair. - title: The title to display on top of the chart. - tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. - x_title: The title given to the x axis. By default, uses the value of the x parameter. - y_title: The title given to the y axis. By default, uses the value of the y parameter. - color_legend_title: The title given to the color legend. By default, uses the value of color parameter. - stroke_dash_legend_title: The title given to the stroke_dash legend. By default, uses the value of the stroke_dash parameter. - color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - stroke_dash_legend_position: The position of the stoke_dash legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - height: The height of the plot in pixels. - width: The width of the plot in pixels. - x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. - y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. - caption: The (optional) caption to display below the plot. - interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. - label: The (optional) label to display on the top left corner of the plot. - show_label: Whether the label should be displayed. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - visible: Whether the plot should be visible. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.x = x - self.y = y - self.color = color - self.stroke_dash = stroke_dash - self.tooltip = tooltip - self.title = title - self.x_title = x_title - self.y_title = y_title - self.color_legend_title = color_legend_title - self.stroke_dash_legend_title = stroke_dash_legend_title - self.color_legend_position = color_legend_position - self.stroke_dash_legend_position = stroke_dash_legend_position - self.overlay_point = overlay_point - self.x_lim = x_lim - self.y_lim = y_lim - self.caption = caption - self.interactive_chart = interactive - self.width = width - self.height = height - super().__init__( - value=value, - label=label, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - every=every, - ) - - def get_config(self): - config = super().get_config() - config["caption"] = self.caption - return config - - def get_block_name(self) -> str: - return "plot" - - @staticmethod - def update( - value: pd.DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE, - x: str | None = None, - y: str | None = None, - color: str | None = None, - stroke_dash: str | None = None, - overlay_point: bool | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - stroke_dash_legend_title: str | None = None, - color_legend_position: str | None = None, - stroke_dash_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - x_lim: list[int] | None = None, - y_lim: list[int] | None = None, - interactive: bool | None = None, - caption: str | None = None, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - ): - """Update an existing plot component. - - If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified. - - Parameters: - value: The pandas dataframe containing the data to display in a scatter plot. - x: Column corresponding to the x axis. - y: Column corresponding to the y axis. - color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. - stroke_dash: The column to determine the symbol used to draw the line, e.g. dashed lines, dashed lines with points. - overlay_point: Whether to draw a point on the line for each (x, y) coordinate pair. - title: The title to display on top of the chart. - tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. - x_title: The title given to the x axis. By default, uses the value of the x parameter. - y_title: The title given to the y axis. By default, uses the value of the y parameter. - color_legend_title: The title given to the color legend. By default, uses the value of color parameter. - stroke_dash_legend_title: The title given to the stroke legend. By default, uses the value of stroke parameter. - color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation - stroke_dash_legend_position: The position of the stoke_dash legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation - height: The height of the plot in pixels. - width: The width of the plot in pixels. - x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. - y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. - caption: The (optional) caption to display below the plot. - interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. - label: The (optional) label to display in the top left corner of the plot. - show_label: Whether the label should be displayed. - visible: Whether the plot should be visible. - """ - properties = [ - x, - y, - color, - stroke_dash, - overlay_point, - title, - tooltip, - x_title, - y_title, - color_legend_title, - stroke_dash_legend_title, - color_legend_position, - stroke_dash_legend_position, - height, - width, - x_lim, - y_lim, - interactive, - ] - if any(properties): - if not isinstance(value, pd.DataFrame): - raise ValueError( - "In order to update plot properties the value parameter " - "must be provided, and it must be a Dataframe. Please pass a value " - "parameter to gr.LinePlot.update." - ) - if x is None or y is None: - raise ValueError( - "In order to update plot properties, the x and y axis data " - "must be specified. Please pass valid values for x an y to " - "gr.LinePlot.update." - ) - chart = LinePlot.create_plot(value, *properties) - value = {"type": "altair", "plot": chart.to_json(), "chart": "line"} - - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "caption": caption, - "__type__": "update", - } - return updated_config - - @staticmethod - def create_plot( - value: pd.DataFrame, - x: str, - y: str, - color: str | None = None, - stroke_dash: str | None = None, - overlay_point: bool | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - stroke_dash_legend_title: str | None = None, - color_legend_position: str | None = None, - stroke_dash_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - x_lim: list[int] | None = None, - y_lim: list[int] | None = None, - interactive: bool | None = None, - ): - """Helper for creating the scatter plot.""" - interactive = True if interactive is None else interactive - encodings = { - "x": alt.X( - x, # type: ignore - title=x_title or x, # type: ignore - scale=AltairPlot.create_scale(x_lim), # type: ignore - ), - "y": alt.Y( - y, # type: ignore - title=y_title or y, # type: ignore - scale=AltairPlot.create_scale(y_lim), # type: ignore - ), - } - properties = {} - if title: - properties["title"] = title - if height: - properties["height"] = height - if width: - properties["width"] = width - - if color: - domain = value[color].unique().tolist() - range_ = list(range(len(domain))) - encodings["color"] = { - "field": color, - "type": "nominal", - "scale": {"domain": domain, "range": range_}, - "legend": AltairPlot.create_legend( - position=color_legend_position, title=color_legend_title or color - ), - } - - highlight = None - if interactive and any([color, stroke_dash]): - highlight = alt.selection( - type="single", # type: ignore - on="mouseover", - fields=[c for c in [color, stroke_dash] if c], - nearest=True, - ) - - if stroke_dash: - stroke_dash = { - "field": stroke_dash, # type: ignore - "legend": AltairPlot.create_legend( # type: ignore - position=stroke_dash_legend_position, # type: ignore - title=stroke_dash_legend_title or stroke_dash, # type: ignore - ), # type: ignore - } # type: ignore - else: - stroke_dash = alt.value(alt.Undefined) # type: ignore - - if tooltip: - encodings["tooltip"] = tooltip - - chart = alt.Chart(value).encode(**encodings) # type: ignore - - points = chart.mark_point(clip=True).encode( - opacity=alt.value(alt.Undefined) if overlay_point else alt.value(0), - ) - lines = chart.mark_line(clip=True).encode(strokeDash=stroke_dash) - - if highlight: - points = points.add_selection(highlight) - - lines = lines.encode( - size=alt.condition(highlight, alt.value(4), alt.value(1)), - ) - - chart = (lines + points).properties(background="transparent", **properties) - if interactive: - chart = chart.interactive() - - return chart - - def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None: - # if None or update - if y is None or isinstance(y, Dict): - return y - if self.x is None or self.y is None: - raise ValueError("No value provided for required parameters `x` and `y`.") - chart = self.create_plot( - value=y, - x=self.x, - y=self.y, - color=self.color, - overlay_point=self.overlay_point, - title=self.title, - tooltip=self.tooltip, - x_title=self.x_title, - y_title=self.y_title, - color_legend_title=self.color_legend_title, - color_legend_position=self.color_legend_position, - stroke_dash_legend_title=self.stroke_dash_legend_title, - stroke_dash_legend_position=self.stroke_dash_legend_position, - x_lim=self.x_lim, - y_lim=self.y_lim, - stroke_dash=self.stroke_dash, - interactive=self.interactive_chart, - height=self.height, - width=self.width, - ) - - return {"type": "altair", "plot": chart.to_json(), "chart": "line"} - - -@document() -class BarPlot(Plot): - """ - Create a bar plot. - - Preprocessing: this component does *not* accept input. - Postprocessing: expects a pandas dataframe with the data to plot. - - Demos: native_plots, chicago-bikeshare-dashboard - """ - - def __init__( - self, - value: pd.DataFrame | Callable | None = None, - x: str | None = None, - y: str | None = None, - *, - color: str | None = None, - vertical: bool = True, - group: str | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - group_title: str | None = None, - color_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - y_lim: list[int] | None = None, - caption: str | None = None, - interactive: bool | None = True, - label: str | None = None, - show_label: bool = True, - every: float | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - ): - """ - Parameters: - value: The pandas dataframe containing the data to display in a scatter plot. - x: Column corresponding to the x axis. - y: Column corresponding to the y axis. - color: The column to determine the bar color. Must be categorical (discrete values). - vertical: If True, the bars will be displayed vertically. If False, the x and y axis will be switched, displaying the bars horizontally. Default is True. - group: The column with which to split the overall plot into smaller subplots. - title: The title to display on top of the chart. - tooltip: The column (or list of columns) to display on the tooltip when a user hovers over a bar. - x_title: The title given to the x axis. By default, uses the value of the x parameter. - y_title: The title given to the y axis. By default, uses the value of the y parameter. - color_legend_title: The title given to the color legend. By default, uses the value of color parameter. - group_title: The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit. - color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - height: The height of the plot in pixels. - width: The width of the plot in pixels. - y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. - caption: The (optional) caption to display below the plot. - interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. - label: The (optional) label to display on the top left corner of the plot. - show_label: Whether the label should be displayed. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - visible: Whether the plot should be visible. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.x = x - self.y = y - self.color = color - self.vertical = vertical - self.group = group - self.group_title = group_title - self.tooltip = tooltip - self.title = title - self.x_title = x_title - self.y_title = y_title - self.color_legend_title = color_legend_title - self.group_title = group_title - self.color_legend_position = color_legend_position - self.y_lim = y_lim - self.caption = caption - self.interactive_chart = interactive - self.width = width - self.height = height - super().__init__( - value=value, - label=label, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - every=every, - ) - - def get_config(self): - config = super().get_config() - config["caption"] = self.caption - return config - - def get_block_name(self) -> str: - return "plot" - - @staticmethod - def update( - value: pd.DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE, - x: str | None = None, - y: str | None = None, - color: str | None = None, - vertical: bool = True, - group: str | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - group_title: str | None = None, - color_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - y_lim: list[int] | None = None, - caption: str | None = None, - interactive: bool | None = None, - label: str | None = None, - show_label: bool = True, - visible: bool = True, - ): - """Update an existing BarPlot component. - - If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified. - - Parameters: - value: The pandas dataframe containing the data to display in a scatter plot. - x: Column corresponding to the x axis. - y: Column corresponding to the y axis. - color: The column to determine the bar color. Must be categorical (discrete values). - vertical: If True, the bars will be displayed vertically. If False, the x and y axis will be switched, displaying the bars horizontally. Default is True. - group: The column with which to split the overall plot into smaller subplots. - title: The title to display on top of the chart. - tooltip: The column (or list of columns) to display on the tooltip when a user hovers over a bar. - x_title: The title given to the x axis. By default, uses the value of the x parameter. - y_title: The title given to the y axis. By default, uses the value of the y parameter. - color_legend_title: The title given to the color legend. By default, uses the value of color parameter. - group_title: The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit. - color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. - height: The height of the plot in pixels. - width: The width of the plot in pixels. - y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. - caption: The (optional) caption to display below the plot. - interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. - label: The (optional) label to display on the top left corner of the plot. - show_label: Whether the label should be displayed. - visible: Whether the plot should be visible. - """ - properties = [ - x, - y, - color, - vertical, - group, - title, - tooltip, - x_title, - y_title, - color_legend_title, - group_title, - color_legend_position, - height, - width, - y_lim, - interactive, - ] - if any(properties): - if not isinstance(value, pd.DataFrame): - raise ValueError( - "In order to update plot properties the value parameter " - "must be provided, and it must be a Dataframe. Please pass a value " - "parameter to gr.BarPlot.update." - ) - if x is None or y is None: - raise ValueError( - "In order to update plot properties, the x and y axis data " - "must be specified. Please pass valid values for x an y to " - "gr.BarPlot.update." - ) - chart = BarPlot.create_plot(value, *properties) - value = {"type": "altair", "plot": chart.to_json(), "chart": "bar"} - - updated_config = { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "caption": caption, - "__type__": "update", - } - return updated_config - - @staticmethod - def create_plot( - value: pd.DataFrame, - x: str, - y: str, - color: str | None = None, - vertical: bool = True, - group: str | None = None, - title: str | None = None, - tooltip: list[str] | str | None = None, - x_title: str | None = None, - y_title: str | None = None, - color_legend_title: str | None = None, - group_title: str | None = None, - color_legend_position: str | None = None, - height: int | None = None, - width: int | None = None, - y_lim: list[int] | None = None, - interactive: bool | None = True, - ): - """Helper for creating the bar plot.""" - interactive = True if interactive is None else interactive - orientation = ( - {"field": group, "title": group_title if group_title is not None else group} - if group - else {} - ) - - x_title = x_title or x - y_title = y_title or y - - # If horizontal, switch x and y - if not vertical: - y, x = x, y - x = f"sum({x}):Q" - y_title, x_title = x_title, y_title - orientation = {"row": alt.Row(**orientation)} if orientation else {} # type: ignore - x_lim = y_lim - y_lim = None - else: - y = f"sum({y}):Q" - x_lim = None - orientation = {"column": alt.Column(**orientation)} if orientation else {} # type: ignore - - encodings = dict( - x=alt.X( - x, # type: ignore - title=x_title, # type: ignore - scale=AltairPlot.create_scale(x_lim), # type: ignore - ), - y=alt.Y( - y, # type: ignore - title=y_title, # type: ignore - scale=AltairPlot.create_scale(y_lim), # type: ignore - ), - **orientation, - ) - properties = {} - if title: - properties["title"] = title - if height: - properties["height"] = height - if width: - properties["width"] = width - - if color: - domain = value[color].unique().tolist() - range_ = list(range(len(domain))) - encodings["color"] = { - "field": color, - "type": "nominal", - "scale": {"domain": domain, "range": range_}, - "legend": AltairPlot.create_legend( - position=color_legend_position, title=color_legend_title or color - ), - } - - if tooltip: - encodings["tooltip"] = tooltip - - chart = ( - alt.Chart(value) # type: ignore - .mark_bar() # type: ignore - .encode(**encodings) - .properties(background="transparent", **properties) - ) - if interactive: - chart = chart.interactive() - - return chart - - def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None: - # if None or update - if y is None or isinstance(y, Dict): - return y - if self.x is None or self.y is None: - raise ValueError("No value provided for required parameters `x` and `y`.") - chart = self.create_plot( - value=y, - x=self.x, - y=self.y, - color=self.color, - vertical=self.vertical, - group=self.group, - title=self.title, - tooltip=self.tooltip, - x_title=self.x_title, - y_title=self.y_title, - color_legend_title=self.color_legend_title, - color_legend_position=self.color_legend_position, - group_title=self.group_title, - y_lim=self.y_lim, - interactive=self.interactive_chart, - height=self.height, - width=self.width, - ) - - return {"type": "altair", "plot": chart.to_json(), "chart": "bar"} - - -@document() -class Markdown(IOComponent, Changeable, StringSerializable): - """ - Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a valid {str} that can be rendered as Markdown. - - Demos: blocks_hello, blocks_kinematics - Guides: key-features - """ - - def __init__( - self, - value: str | Callable = "", - *, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Value to show in Markdown component. If callable, the function will be called whenever the app loads to set the initial value of the component. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - self.md = utils.get_markdown_parser() - IOComponent.__init__( - self, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def postprocess(self, y: str | None) -> str | None: - """ - Parameters: - y: markdown representation - Returns: - HTML rendering of markdown - """ - if y is None: - return None - unindented_y = inspect.cleandoc(y) - return self.md.render(unindented_y) - - def get_config(self): - return { - "value": self.value, - **Component.get_config(self), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - visible: bool | None = None, - ): - updated_config = { - "visible": visible, - "value": value, - "__type__": "update", - } - return updated_config - - def style(self): - return self - - def as_example(self, input_data: str | None) -> str: - postprocessed = self.postprocess(input_data) - return postprocessed if postprocessed else "" - - -@document("languages") -class Code(Changeable, Inputable, IOComponent, StringSerializable): - """ - Creates a Code editor for entering, editing or viewing code. - Preprocessing: passes a {str} of code into the function. - Postprocessing: expects the function to return a {str} of code or a single-elment {tuple}: (string filepath,) - """ - - languages = [ - "python", - "markdown", - "json", - "html", - "css", - "javascript", - "typescript", - "yaml", - "dockerfile", - "shell", - "r", - None, - ] - - def __init__( - self, - value: str | tuple[str] | None = None, - language: str | None = None, - *, - lines: int = 5, - label: str | None = None, - interactive: bool | None = None, - show_label: bool = True, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - value: Default value to show in the code editor. If callable, the function will be called whenever the app loads to set the initial value of the component. - language: The language to display the code as. Supported languages listed in `gr.Code.languages`. - label: component name in interface. - interactive: Whether user should be able to enter code or only view it. - show_label: if True, will display label. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - assert language in Code.languages, f"Language {language} not supported." - self.language = language - self.lines = lines - IOComponent.__init__( - self, - label=label, - interactive=interactive, - show_label=show_label, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - - def get_config(self): - return { - "value": self.value, - "language": self.language, - "lines": self.lines, - **IOComponent.get_config(self), - } - - def postprocess(self, y): - if y is None: - return None - elif isinstance(y, tuple): - with open(y[0]) as file_data: - return file_data.read() - else: - return y.strip() - - @staticmethod - def update( - value: str - | tuple[str] - | None - | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE, - label: str | None = None, - show_label: bool | None = None, - visible: bool | None = None, - language: str | None = None, - interactive: bool | None = None, - ): - return { - "label": label, - "show_label": show_label, - "visible": visible, - "value": value, - "language": language, - "interactive": interactive, - "__type__": "update", - } - - def style(self): - return self - - -############################ -# Special Components -############################ - - -@document("style") -class Dataset(Clickable, Selectable, Component, StringSerializable): - """ - Used to create an output widget for showing datasets. Used to render the examples - box. - Preprocessing: passes the selected sample either as a {list} of data (if type="value") or as an {int} index (if type="index") - Postprocessing: expects a {list} of {lists} corresponding to the dataset data. - """ - - def __init__( - self, - *, - label: str | None = None, - components: list[IOComponent] | list[str], - samples: list[list[Any]] | None = None, - headers: list[str] | None = None, - type: str = "values", - samples_per_page: int = 10, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - components: Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video - samples: a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component - headers: Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels - type: 'values' if clicking on a sample should pass the value of the sample, or "index" if it should pass the index of the sample - samples_per_page: how many examples to show per page. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - Component.__init__( - self, visible=visible, elem_id=elem_id, elem_classes=elem_classes, **kwargs - ) - self.components = [get_component_instance(c, render=False) for c in components] - - # Narrow type to IOComponent - assert all( - isinstance(c, IOComponent) for c in self.components - ), "All components in a `Dataset` must be subclasses of `IOComponent`" - self.components = [c for c in self.components if isinstance(c, IOComponent)] - for component in self.components: - component.root_url = self.root_url - - self.samples = [[]] if samples is None else samples - for example in self.samples: - for i, (component, ex) in enumerate(zip(self.components, example)): - example[i] = component.as_example(ex) - self.type = type - self.label = label - if headers is not None: - self.headers = headers - elif all(c.label is None for c in self.components): - self.headers = [] - else: - self.headers = [c.label or "" for c in self.components] - self.samples_per_page = samples_per_page - - def get_config(self): - return { - "components": [component.get_block_name() for component in self.components], - "headers": self.headers, - "samples": self.samples, - "type": self.type, - "label": self.label, - "samples_per_page": self.samples_per_page, - **Component.get_config(self), - } - - @staticmethod - def update( - samples: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - visible: bool | None = None, - label: str | None = None, - ): - return { - "samples": samples, - "visible": visible, - "label": label, - "__type__": "update", - } - - def preprocess(self, x: Any) -> Any: - """ - Any preprocessing needed to be performed on function input. - """ - if self.type == "index": - return x - elif self.type == "values": - return self.samples[x] - - def postprocess(self, samples: list[list[Any]]) -> dict: - return { - "samples": samples, - "__type__": "update", - } - - def style(self, **kwargs): - """ - This method can be used to change the appearance of the Dataset component. - """ - Component.style(self, **kwargs) - return self - - -@document() -class Interpretation(Component, SimpleSerializable): - """ - Used to create an interpretation widget for a component. - Preprocessing: this component does *not* accept input. - Postprocessing: expects a {dict} with keys "original" and "interpretation". - - Guides: custom-interpretations-with-blocks - """ - - def __init__( - self, - component: Component, - *, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - **kwargs, - ): - """ - Parameters: - component: Which component to show in the interpretation widget. - visible: Whether or not the interpretation is visible. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - """ - Component.__init__( - self, visible=visible, elem_id=elem_id, elem_classes=elem_classes, **kwargs - ) - self.component = component - - def get_config(self): - return { - "component": self.component.get_block_name(), - "component_props": self.component.get_config(), - } - - @staticmethod - def update( - value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - visible: bool | None = None, - ): - return { - "visible": visible, - "value": value, - "__type__": "update", - } - - def style(self): - return self - - -class StatusTracker(Component, SimpleSerializable): - def __init__( - self, - **kwargs, - ): - warnings.warn("The StatusTracker component is deprecated.") - - -def component(cls_name: str) -> Component: - obj = utils.component_or_layout_class(cls_name)() - if isinstance(obj, BlockContext): - raise ValueError(f"Invalid component: {obj.__class__}") - return obj - - -def get_component_instance(comp: str | dict | Component, render=True) -> Component: - if isinstance(comp, str): - component_obj = component(comp) - if not (render): - component_obj.unrender() - return component_obj - elif isinstance(comp, dict): - name = comp.pop("name") - component_cls = utils.component_or_layout_class(name) - component_obj = component_cls(**comp) - if isinstance(component_obj, BlockContext): - raise ValueError(f"Invalid component: {name}") - if not (render): - component_obj.unrender() - return component_obj - elif isinstance(comp, Component): - return comp - else: - raise ValueError( - f"Component must provided as a `str` or `dict` or `Component` but is {comp}" - ) - - -Text = Textbox -DataFrame = Dataframe -Highlightedtext = HighlightedText -Annotatedimage = AnnotatedImage -Highlight = HighlightedText -Checkboxgroup = CheckboxGroup -TimeSeries = Timeseries -Json = JSON diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_multipart.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_multipart.py deleted file mode 100644 index 446f4ad2df3eb0b566e11c9aab9bbfc4875edfba..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_multipart.py +++ /dev/null @@ -1,267 +0,0 @@ -import binascii -import io -import os -import typing -from pathlib import Path - -from ._types import ( - AsyncByteStream, - FileContent, - FileTypes, - RequestData, - RequestFiles, - SyncByteStream, -) -from ._utils import ( - format_form_param, - guess_content_type, - peek_filelike_length, - primitive_value_to_str, - to_bytes, -) - - -def get_multipart_boundary_from_content_type( - content_type: typing.Optional[bytes], -) -> typing.Optional[bytes]: - if not content_type or not content_type.startswith(b"multipart/form-data"): - return None - # parse boundary according to - # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 - if b";" in content_type: - for section in content_type.split(b";"): - if section.strip().lower().startswith(b"boundary="): - return section.strip()[len(b"boundary=") :].strip(b'"') - return None - - -class DataField: - """ - A single form field item, within a multipart form field. - """ - - def __init__( - self, name: str, value: typing.Union[str, bytes, int, float, None] - ) -> None: - if not isinstance(name, str): - raise TypeError( - f"Invalid type for name. Expected str, got {type(name)}: {name!r}" - ) - if value is not None and not isinstance(value, (str, bytes, int, float)): - raise TypeError( - f"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}" - ) - self.name = name - self.value: typing.Union[str, bytes] = ( - value if isinstance(value, bytes) else primitive_value_to_str(value) - ) - - def render_headers(self) -> bytes: - if not hasattr(self, "_headers"): - name = format_form_param("name", self.name) - self._headers = b"".join( - [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] - ) - - return self._headers - - def render_data(self) -> bytes: - if not hasattr(self, "_data"): - self._data = to_bytes(self.value) - - return self._data - - def get_length(self) -> int: - headers = self.render_headers() - data = self.render_data() - return len(headers) + len(data) - - def render(self) -> typing.Iterator[bytes]: - yield self.render_headers() - yield self.render_data() - - -class FileField: - """ - A single file field item, within a multipart form field. - """ - - CHUNK_SIZE = 64 * 1024 - - def __init__(self, name: str, value: FileTypes) -> None: - self.name = name - - fileobj: FileContent - - headers: typing.Dict[str, str] = {} - content_type: typing.Optional[str] = None - - # This large tuple based API largely mirror's requests' API - # It would be good to think of better APIs for this that we could include in httpx 2.0 - # since variable length tuples (especially of 4 elements) are quite unwieldly - if isinstance(value, tuple): - if len(value) == 2: - # neither the 3rd parameter (content_type) nor the 4th (headers) was included - filename, fileobj = value # type: ignore - elif len(value) == 3: - filename, fileobj, content_type = value # type: ignore - else: - # all 4 parameters included - filename, fileobj, content_type, headers = value # type: ignore - else: - filename = Path(str(getattr(value, "name", "upload"))).name - fileobj = value - - if content_type is None: - content_type = guess_content_type(filename) - - has_content_type_header = any("content-type" in key.lower() for key in headers) - if content_type is not None and not has_content_type_header: - # note that unlike requests, we ignore the content_type - # provided in the 3rd tuple element if it is also included in the headers - # requests does the opposite (it overwrites the header with the 3rd tuple element) - headers["Content-Type"] = content_type - - if isinstance(fileobj, io.StringIO): - raise TypeError( - "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." - ) - if isinstance(fileobj, io.TextIOBase): - raise TypeError( - "Multipart file uploads must be opened in binary mode, not text mode." - ) - - self.filename = filename - self.file = fileobj - self.headers = headers - - def get_length(self) -> typing.Optional[int]: - headers = self.render_headers() - - if isinstance(self.file, (str, bytes)): - return len(headers) + len(to_bytes(self.file)) - - file_length = peek_filelike_length(self.file) - - # If we can't determine the filesize without reading it into memory, - # then return `None` here, to indicate an unknown file length. - if file_length is None: - return None - - return len(headers) + file_length - - def render_headers(self) -> bytes: - if not hasattr(self, "_headers"): - parts = [ - b"Content-Disposition: form-data; ", - format_form_param("name", self.name), - ] - if self.filename: - filename = format_form_param("filename", self.filename) - parts.extend([b"; ", filename]) - for header_name, header_value in self.headers.items(): - key, val = f"\r\n{header_name}: ".encode(), header_value.encode() - parts.extend([key, val]) - parts.append(b"\r\n\r\n") - self._headers = b"".join(parts) - - return self._headers - - def render_data(self) -> typing.Iterator[bytes]: - if isinstance(self.file, (str, bytes)): - yield to_bytes(self.file) - return - - if hasattr(self.file, "seek"): - try: - self.file.seek(0) - except io.UnsupportedOperation: - pass - - chunk = self.file.read(self.CHUNK_SIZE) - while chunk: - yield to_bytes(chunk) - chunk = self.file.read(self.CHUNK_SIZE) - - def render(self) -> typing.Iterator[bytes]: - yield self.render_headers() - yield from self.render_data() - - -class MultipartStream(SyncByteStream, AsyncByteStream): - """ - Request content as streaming multipart encoded form data. - """ - - def __init__( - self, - data: RequestData, - files: RequestFiles, - boundary: typing.Optional[bytes] = None, - ) -> None: - if boundary is None: - boundary = binascii.hexlify(os.urandom(16)) - - self.boundary = boundary - self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( - "ascii" - ) - self.fields = list(self._iter_fields(data, files)) - - def _iter_fields( - self, data: RequestData, files: RequestFiles - ) -> typing.Iterator[typing.Union[FileField, DataField]]: - for name, value in data.items(): - if isinstance(value, (tuple, list)): - for item in value: - yield DataField(name=name, value=item) - else: - yield DataField(name=name, value=value) - - file_items = files.items() if isinstance(files, typing.Mapping) else files - for name, value in file_items: - yield FileField(name=name, value=value) - - def iter_chunks(self) -> typing.Iterator[bytes]: - for field in self.fields: - yield b"--%s\r\n" % self.boundary - yield from field.render() - yield b"\r\n" - yield b"--%s--\r\n" % self.boundary - - def get_content_length(self) -> typing.Optional[int]: - """ - Return the length of the multipart encoded content, or `None` if - any of the files have a length that cannot be determined upfront. - """ - boundary_length = len(self.boundary) - length = 0 - - for field in self.fields: - field_length = field.get_length() - if field_length is None: - return None - - length += 2 + boundary_length + 2 # b"--{boundary}\r\n" - length += field_length - length += 2 # b"\r\n" - - length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" - return length - - # Content stream interface. - - def get_headers(self) -> typing.Dict[str, str]: - content_length = self.get_content_length() - content_type = self.content_type - if content_length is None: - return {"Transfer-Encoding": "chunked", "Content-Type": content_type} - return {"Content-Length": str(content_length), "Content-Type": content_type} - - def __iter__(self) -> typing.Iterator[bytes]: - for chunk in self.iter_chunks(): - yield chunk - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - for chunk in self.iter_chunks(): - yield chunk diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/matplotlib/_cm_listed.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/matplotlib/_cm_listed.py deleted file mode 100644 index a331ad74a5f03688005dc14d5867653b3d77e20c..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/matplotlib/_cm_listed.py +++ /dev/null @@ -1,2071 +0,0 @@ -from .colors import ListedColormap - -_magma_data = [[0.001462, 0.000466, 0.013866], - [0.002258, 0.001295, 0.018331], - [0.003279, 0.002305, 0.023708], - [0.004512, 0.003490, 0.029965], - [0.005950, 0.004843, 0.037130], - [0.007588, 0.006356, 0.044973], - [0.009426, 0.008022, 0.052844], - [0.011465, 0.009828, 0.060750], - [0.013708, 0.011771, 0.068667], - [0.016156, 0.013840, 0.076603], - [0.018815, 0.016026, 0.084584], - [0.021692, 0.018320, 0.092610], - [0.024792, 0.020715, 0.100676], - [0.028123, 0.023201, 0.108787], - [0.031696, 0.025765, 0.116965], - [0.035520, 0.028397, 0.125209], - [0.039608, 0.031090, 0.133515], - [0.043830, 0.033830, 0.141886], - [0.048062, 0.036607, 0.150327], - [0.052320, 0.039407, 0.158841], - [0.056615, 0.042160, 0.167446], - [0.060949, 0.044794, 0.176129], - [0.065330, 0.047318, 0.184892], - [0.069764, 0.049726, 0.193735], - [0.074257, 0.052017, 0.202660], - [0.078815, 0.054184, 0.211667], - [0.083446, 0.056225, 0.220755], - [0.088155, 0.058133, 0.229922], - [0.092949, 0.059904, 0.239164], - [0.097833, 0.061531, 0.248477], - [0.102815, 0.063010, 0.257854], - [0.107899, 0.064335, 0.267289], - [0.113094, 0.065492, 0.276784], - [0.118405, 0.066479, 0.286321], - [0.123833, 0.067295, 0.295879], - [0.129380, 0.067935, 0.305443], - [0.135053, 0.068391, 0.315000], - [0.140858, 0.068654, 0.324538], - [0.146785, 0.068738, 0.334011], - [0.152839, 0.068637, 0.343404], - [0.159018, 0.068354, 0.352688], - [0.165308, 0.067911, 0.361816], - [0.171713, 0.067305, 0.370771], - [0.178212, 0.066576, 0.379497], - [0.184801, 0.065732, 0.387973], - [0.191460, 0.064818, 0.396152], - [0.198177, 0.063862, 0.404009], - [0.204935, 0.062907, 0.411514], - [0.211718, 0.061992, 0.418647], - [0.218512, 0.061158, 0.425392], - [0.225302, 0.060445, 0.431742], - [0.232077, 0.059889, 0.437695], - [0.238826, 0.059517, 0.443256], - [0.245543, 0.059352, 0.448436], - [0.252220, 0.059415, 0.453248], - [0.258857, 0.059706, 0.457710], - [0.265447, 0.060237, 0.461840], - [0.271994, 0.060994, 0.465660], - [0.278493, 0.061978, 0.469190], - [0.284951, 0.063168, 0.472451], - [0.291366, 0.064553, 0.475462], - [0.297740, 0.066117, 0.478243], - [0.304081, 0.067835, 0.480812], - [0.310382, 0.069702, 0.483186], - [0.316654, 0.071690, 0.485380], - [0.322899, 0.073782, 0.487408], - [0.329114, 0.075972, 0.489287], - [0.335308, 0.078236, 0.491024], - [0.341482, 0.080564, 0.492631], - [0.347636, 0.082946, 0.494121], - [0.353773, 0.085373, 0.495501], - [0.359898, 0.087831, 0.496778], - [0.366012, 0.090314, 0.497960], - [0.372116, 0.092816, 0.499053], - [0.378211, 0.095332, 0.500067], - [0.384299, 0.097855, 0.501002], - [0.390384, 0.100379, 0.501864], - [0.396467, 0.102902, 0.502658], - [0.402548, 0.105420, 0.503386], - [0.408629, 0.107930, 0.504052], - [0.414709, 0.110431, 0.504662], - [0.420791, 0.112920, 0.505215], - [0.426877, 0.115395, 0.505714], - [0.432967, 0.117855, 0.506160], - [0.439062, 0.120298, 0.506555], - [0.445163, 0.122724, 0.506901], - [0.451271, 0.125132, 0.507198], - [0.457386, 0.127522, 0.507448], - [0.463508, 0.129893, 0.507652], - [0.469640, 0.132245, 0.507809], - [0.475780, 0.134577, 0.507921], - [0.481929, 0.136891, 0.507989], - [0.488088, 0.139186, 0.508011], - [0.494258, 0.141462, 0.507988], - [0.500438, 0.143719, 0.507920], - [0.506629, 0.145958, 0.507806], - [0.512831, 0.148179, 0.507648], - [0.519045, 0.150383, 0.507443], - [0.525270, 0.152569, 0.507192], - [0.531507, 0.154739, 0.506895], - [0.537755, 0.156894, 0.506551], - [0.544015, 0.159033, 0.506159], - [0.550287, 0.161158, 0.505719], - [0.556571, 0.163269, 0.505230], - [0.562866, 0.165368, 0.504692], - [0.569172, 0.167454, 0.504105], - [0.575490, 0.169530, 0.503466], - [0.581819, 0.171596, 0.502777], - [0.588158, 0.173652, 0.502035], - [0.594508, 0.175701, 0.501241], - [0.600868, 0.177743, 0.500394], - [0.607238, 0.179779, 0.499492], - [0.613617, 0.181811, 0.498536], - [0.620005, 0.183840, 0.497524], - [0.626401, 0.185867, 0.496456], - [0.632805, 0.187893, 0.495332], - [0.639216, 0.189921, 0.494150], - [0.645633, 0.191952, 0.492910], - [0.652056, 0.193986, 0.491611], - [0.658483, 0.196027, 0.490253], - [0.664915, 0.198075, 0.488836], - [0.671349, 0.200133, 0.487358], - [0.677786, 0.202203, 0.485819], - [0.684224, 0.204286, 0.484219], - [0.690661, 0.206384, 0.482558], - [0.697098, 0.208501, 0.480835], - [0.703532, 0.210638, 0.479049], - [0.709962, 0.212797, 0.477201], - [0.716387, 0.214982, 0.475290], - [0.722805, 0.217194, 0.473316], - [0.729216, 0.219437, 0.471279], - [0.735616, 0.221713, 0.469180], - [0.742004, 0.224025, 0.467018], - [0.748378, 0.226377, 0.464794], - [0.754737, 0.228772, 0.462509], - [0.761077, 0.231214, 0.460162], - [0.767398, 0.233705, 0.457755], - [0.773695, 0.236249, 0.455289], - [0.779968, 0.238851, 0.452765], - [0.786212, 0.241514, 0.450184], - [0.792427, 0.244242, 0.447543], - [0.798608, 0.247040, 0.444848], - [0.804752, 0.249911, 0.442102], - [0.810855, 0.252861, 0.439305], - [0.816914, 0.255895, 0.436461], - [0.822926, 0.259016, 0.433573], - [0.828886, 0.262229, 0.430644], - [0.834791, 0.265540, 0.427671], - [0.840636, 0.268953, 0.424666], - [0.846416, 0.272473, 0.421631], - [0.852126, 0.276106, 0.418573], - [0.857763, 0.279857, 0.415496], - [0.863320, 0.283729, 0.412403], - [0.868793, 0.287728, 0.409303], - [0.874176, 0.291859, 0.406205], - [0.879464, 0.296125, 0.403118], - [0.884651, 0.300530, 0.400047], - [0.889731, 0.305079, 0.397002], - [0.894700, 0.309773, 0.393995], - [0.899552, 0.314616, 0.391037], - [0.904281, 0.319610, 0.388137], - [0.908884, 0.324755, 0.385308], - [0.913354, 0.330052, 0.382563], - [0.917689, 0.335500, 0.379915], - [0.921884, 0.341098, 0.377376], - [0.925937, 0.346844, 0.374959], - [0.929845, 0.352734, 0.372677], - [0.933606, 0.358764, 0.370541], - [0.937221, 0.364929, 0.368567], - [0.940687, 0.371224, 0.366762], - [0.944006, 0.377643, 0.365136], - [0.947180, 0.384178, 0.363701], - [0.950210, 0.390820, 0.362468], - [0.953099, 0.397563, 0.361438], - [0.955849, 0.404400, 0.360619], - [0.958464, 0.411324, 0.360014], - [0.960949, 0.418323, 0.359630], - [0.963310, 0.425390, 0.359469], - [0.965549, 0.432519, 0.359529], - [0.967671, 0.439703, 0.359810], - [0.969680, 0.446936, 0.360311], - [0.971582, 0.454210, 0.361030], - [0.973381, 0.461520, 0.361965], - [0.975082, 0.468861, 0.363111], - [0.976690, 0.476226, 0.364466], - [0.978210, 0.483612, 0.366025], - [0.979645, 0.491014, 0.367783], - [0.981000, 0.498428, 0.369734], - [0.982279, 0.505851, 0.371874], - [0.983485, 0.513280, 0.374198], - [0.984622, 0.520713, 0.376698], - [0.985693, 0.528148, 0.379371], - [0.986700, 0.535582, 0.382210], - [0.987646, 0.543015, 0.385210], - [0.988533, 0.550446, 0.388365], - [0.989363, 0.557873, 0.391671], - [0.990138, 0.565296, 0.395122], - [0.990871, 0.572706, 0.398714], - [0.991558, 0.580107, 0.402441], - [0.992196, 0.587502, 0.406299], - [0.992785, 0.594891, 0.410283], - [0.993326, 0.602275, 0.414390], - [0.993834, 0.609644, 0.418613], - [0.994309, 0.616999, 0.422950], - [0.994738, 0.624350, 0.427397], - [0.995122, 0.631696, 0.431951], - [0.995480, 0.639027, 0.436607], - [0.995810, 0.646344, 0.441361], - [0.996096, 0.653659, 0.446213], - [0.996341, 0.660969, 0.451160], - [0.996580, 0.668256, 0.456192], - [0.996775, 0.675541, 0.461314], - [0.996925, 0.682828, 0.466526], - [0.997077, 0.690088, 0.471811], - [0.997186, 0.697349, 0.477182], - [0.997254, 0.704611, 0.482635], - [0.997325, 0.711848, 0.488154], - [0.997351, 0.719089, 0.493755], - [0.997351, 0.726324, 0.499428], - [0.997341, 0.733545, 0.505167], - [0.997285, 0.740772, 0.510983], - [0.997228, 0.747981, 0.516859], - [0.997138, 0.755190, 0.522806], - [0.997019, 0.762398, 0.528821], - [0.996898, 0.769591, 0.534892], - [0.996727, 0.776795, 0.541039], - [0.996571, 0.783977, 0.547233], - [0.996369, 0.791167, 0.553499], - [0.996162, 0.798348, 0.559820], - [0.995932, 0.805527, 0.566202], - [0.995680, 0.812706, 0.572645], - [0.995424, 0.819875, 0.579140], - [0.995131, 0.827052, 0.585701], - [0.994851, 0.834213, 0.592307], - [0.994524, 0.841387, 0.598983], - [0.994222, 0.848540, 0.605696], - [0.993866, 0.855711, 0.612482], - [0.993545, 0.862859, 0.619299], - [0.993170, 0.870024, 0.626189], - [0.992831, 0.877168, 0.633109], - [0.992440, 0.884330, 0.640099], - [0.992089, 0.891470, 0.647116], - [0.991688, 0.898627, 0.654202], - [0.991332, 0.905763, 0.661309], - [0.990930, 0.912915, 0.668481], - [0.990570, 0.920049, 0.675675], - [0.990175, 0.927196, 0.682926], - [0.989815, 0.934329, 0.690198], - [0.989434, 0.941470, 0.697519], - [0.989077, 0.948604, 0.704863], - [0.988717, 0.955742, 0.712242], - [0.988367, 0.962878, 0.719649], - [0.988033, 0.970012, 0.727077], - [0.987691, 0.977154, 0.734536], - [0.987387, 0.984288, 0.742002], - [0.987053, 0.991438, 0.749504]] - -_inferno_data = [[0.001462, 0.000466, 0.013866], - [0.002267, 0.001270, 0.018570], - [0.003299, 0.002249, 0.024239], - [0.004547, 0.003392, 0.030909], - [0.006006, 0.004692, 0.038558], - [0.007676, 0.006136, 0.046836], - [0.009561, 0.007713, 0.055143], - [0.011663, 0.009417, 0.063460], - [0.013995, 0.011225, 0.071862], - [0.016561, 0.013136, 0.080282], - [0.019373, 0.015133, 0.088767], - [0.022447, 0.017199, 0.097327], - [0.025793, 0.019331, 0.105930], - [0.029432, 0.021503, 0.114621], - [0.033385, 0.023702, 0.123397], - [0.037668, 0.025921, 0.132232], - [0.042253, 0.028139, 0.141141], - [0.046915, 0.030324, 0.150164], - [0.051644, 0.032474, 0.159254], - [0.056449, 0.034569, 0.168414], - [0.061340, 0.036590, 0.177642], - [0.066331, 0.038504, 0.186962], - [0.071429, 0.040294, 0.196354], - [0.076637, 0.041905, 0.205799], - [0.081962, 0.043328, 0.215289], - [0.087411, 0.044556, 0.224813], - [0.092990, 0.045583, 0.234358], - [0.098702, 0.046402, 0.243904], - [0.104551, 0.047008, 0.253430], - [0.110536, 0.047399, 0.262912], - [0.116656, 0.047574, 0.272321], - [0.122908, 0.047536, 0.281624], - [0.129285, 0.047293, 0.290788], - [0.135778, 0.046856, 0.299776], - [0.142378, 0.046242, 0.308553], - [0.149073, 0.045468, 0.317085], - [0.155850, 0.044559, 0.325338], - [0.162689, 0.043554, 0.333277], - [0.169575, 0.042489, 0.340874], - [0.176493, 0.041402, 0.348111], - [0.183429, 0.040329, 0.354971], - [0.190367, 0.039309, 0.361447], - [0.197297, 0.038400, 0.367535], - [0.204209, 0.037632, 0.373238], - [0.211095, 0.037030, 0.378563], - [0.217949, 0.036615, 0.383522], - [0.224763, 0.036405, 0.388129], - [0.231538, 0.036405, 0.392400], - [0.238273, 0.036621, 0.396353], - [0.244967, 0.037055, 0.400007], - [0.251620, 0.037705, 0.403378], - [0.258234, 0.038571, 0.406485], - [0.264810, 0.039647, 0.409345], - [0.271347, 0.040922, 0.411976], - [0.277850, 0.042353, 0.414392], - [0.284321, 0.043933, 0.416608], - [0.290763, 0.045644, 0.418637], - [0.297178, 0.047470, 0.420491], - [0.303568, 0.049396, 0.422182], - [0.309935, 0.051407, 0.423721], - [0.316282, 0.053490, 0.425116], - [0.322610, 0.055634, 0.426377], - [0.328921, 0.057827, 0.427511], - [0.335217, 0.060060, 0.428524], - [0.341500, 0.062325, 0.429425], - [0.347771, 0.064616, 0.430217], - [0.354032, 0.066925, 0.430906], - [0.360284, 0.069247, 0.431497], - [0.366529, 0.071579, 0.431994], - [0.372768, 0.073915, 0.432400], - [0.379001, 0.076253, 0.432719], - [0.385228, 0.078591, 0.432955], - [0.391453, 0.080927, 0.433109], - [0.397674, 0.083257, 0.433183], - [0.403894, 0.085580, 0.433179], - [0.410113, 0.087896, 0.433098], - [0.416331, 0.090203, 0.432943], - [0.422549, 0.092501, 0.432714], - [0.428768, 0.094790, 0.432412], - [0.434987, 0.097069, 0.432039], - [0.441207, 0.099338, 0.431594], - [0.447428, 0.101597, 0.431080], - [0.453651, 0.103848, 0.430498], - [0.459875, 0.106089, 0.429846], - [0.466100, 0.108322, 0.429125], - [0.472328, 0.110547, 0.428334], - [0.478558, 0.112764, 0.427475], - [0.484789, 0.114974, 0.426548], - [0.491022, 0.117179, 0.425552], - [0.497257, 0.119379, 0.424488], - [0.503493, 0.121575, 0.423356], - [0.509730, 0.123769, 0.422156], - [0.515967, 0.125960, 0.420887], - [0.522206, 0.128150, 0.419549], - [0.528444, 0.130341, 0.418142], - [0.534683, 0.132534, 0.416667], - [0.540920, 0.134729, 0.415123], - [0.547157, 0.136929, 0.413511], - [0.553392, 0.139134, 0.411829], - [0.559624, 0.141346, 0.410078], - [0.565854, 0.143567, 0.408258], - [0.572081, 0.145797, 0.406369], - [0.578304, 0.148039, 0.404411], - [0.584521, 0.150294, 0.402385], - [0.590734, 0.152563, 0.400290], - [0.596940, 0.154848, 0.398125], - [0.603139, 0.157151, 0.395891], - [0.609330, 0.159474, 0.393589], - [0.615513, 0.161817, 0.391219], - [0.621685, 0.164184, 0.388781], - [0.627847, 0.166575, 0.386276], - [0.633998, 0.168992, 0.383704], - [0.640135, 0.171438, 0.381065], - [0.646260, 0.173914, 0.378359], - [0.652369, 0.176421, 0.375586], - [0.658463, 0.178962, 0.372748], - [0.664540, 0.181539, 0.369846], - [0.670599, 0.184153, 0.366879], - [0.676638, 0.186807, 0.363849], - [0.682656, 0.189501, 0.360757], - [0.688653, 0.192239, 0.357603], - [0.694627, 0.195021, 0.354388], - [0.700576, 0.197851, 0.351113], - [0.706500, 0.200728, 0.347777], - [0.712396, 0.203656, 0.344383], - [0.718264, 0.206636, 0.340931], - [0.724103, 0.209670, 0.337424], - [0.729909, 0.212759, 0.333861], - [0.735683, 0.215906, 0.330245], - [0.741423, 0.219112, 0.326576], - [0.747127, 0.222378, 0.322856], - [0.752794, 0.225706, 0.319085], - [0.758422, 0.229097, 0.315266], - [0.764010, 0.232554, 0.311399], - [0.769556, 0.236077, 0.307485], - [0.775059, 0.239667, 0.303526], - [0.780517, 0.243327, 0.299523], - [0.785929, 0.247056, 0.295477], - [0.791293, 0.250856, 0.291390], - [0.796607, 0.254728, 0.287264], - [0.801871, 0.258674, 0.283099], - [0.807082, 0.262692, 0.278898], - [0.812239, 0.266786, 0.274661], - [0.817341, 0.270954, 0.270390], - [0.822386, 0.275197, 0.266085], - [0.827372, 0.279517, 0.261750], - [0.832299, 0.283913, 0.257383], - [0.837165, 0.288385, 0.252988], - [0.841969, 0.292933, 0.248564], - [0.846709, 0.297559, 0.244113], - [0.851384, 0.302260, 0.239636], - [0.855992, 0.307038, 0.235133], - [0.860533, 0.311892, 0.230606], - [0.865006, 0.316822, 0.226055], - [0.869409, 0.321827, 0.221482], - [0.873741, 0.326906, 0.216886], - [0.878001, 0.332060, 0.212268], - [0.882188, 0.337287, 0.207628], - [0.886302, 0.342586, 0.202968], - [0.890341, 0.347957, 0.198286], - [0.894305, 0.353399, 0.193584], - [0.898192, 0.358911, 0.188860], - [0.902003, 0.364492, 0.184116], - [0.905735, 0.370140, 0.179350], - [0.909390, 0.375856, 0.174563], - [0.912966, 0.381636, 0.169755], - [0.916462, 0.387481, 0.164924], - [0.919879, 0.393389, 0.160070], - [0.923215, 0.399359, 0.155193], - [0.926470, 0.405389, 0.150292], - [0.929644, 0.411479, 0.145367], - [0.932737, 0.417627, 0.140417], - [0.935747, 0.423831, 0.135440], - [0.938675, 0.430091, 0.130438], - [0.941521, 0.436405, 0.125409], - [0.944285, 0.442772, 0.120354], - [0.946965, 0.449191, 0.115272], - [0.949562, 0.455660, 0.110164], - [0.952075, 0.462178, 0.105031], - [0.954506, 0.468744, 0.099874], - [0.956852, 0.475356, 0.094695], - [0.959114, 0.482014, 0.089499], - [0.961293, 0.488716, 0.084289], - [0.963387, 0.495462, 0.079073], - [0.965397, 0.502249, 0.073859], - [0.967322, 0.509078, 0.068659], - [0.969163, 0.515946, 0.063488], - [0.970919, 0.522853, 0.058367], - [0.972590, 0.529798, 0.053324], - [0.974176, 0.536780, 0.048392], - [0.975677, 0.543798, 0.043618], - [0.977092, 0.550850, 0.039050], - [0.978422, 0.557937, 0.034931], - [0.979666, 0.565057, 0.031409], - [0.980824, 0.572209, 0.028508], - [0.981895, 0.579392, 0.026250], - [0.982881, 0.586606, 0.024661], - [0.983779, 0.593849, 0.023770], - [0.984591, 0.601122, 0.023606], - [0.985315, 0.608422, 0.024202], - [0.985952, 0.615750, 0.025592], - [0.986502, 0.623105, 0.027814], - [0.986964, 0.630485, 0.030908], - [0.987337, 0.637890, 0.034916], - [0.987622, 0.645320, 0.039886], - [0.987819, 0.652773, 0.045581], - [0.987926, 0.660250, 0.051750], - [0.987945, 0.667748, 0.058329], - [0.987874, 0.675267, 0.065257], - [0.987714, 0.682807, 0.072489], - [0.987464, 0.690366, 0.079990], - [0.987124, 0.697944, 0.087731], - [0.986694, 0.705540, 0.095694], - [0.986175, 0.713153, 0.103863], - [0.985566, 0.720782, 0.112229], - [0.984865, 0.728427, 0.120785], - [0.984075, 0.736087, 0.129527], - [0.983196, 0.743758, 0.138453], - [0.982228, 0.751442, 0.147565], - [0.981173, 0.759135, 0.156863], - [0.980032, 0.766837, 0.166353], - [0.978806, 0.774545, 0.176037], - [0.977497, 0.782258, 0.185923], - [0.976108, 0.789974, 0.196018], - [0.974638, 0.797692, 0.206332], - [0.973088, 0.805409, 0.216877], - [0.971468, 0.813122, 0.227658], - [0.969783, 0.820825, 0.238686], - [0.968041, 0.828515, 0.249972], - [0.966243, 0.836191, 0.261534], - [0.964394, 0.843848, 0.273391], - [0.962517, 0.851476, 0.285546], - [0.960626, 0.859069, 0.298010], - [0.958720, 0.866624, 0.310820], - [0.956834, 0.874129, 0.323974], - [0.954997, 0.881569, 0.337475], - [0.953215, 0.888942, 0.351369], - [0.951546, 0.896226, 0.365627], - [0.950018, 0.903409, 0.380271], - [0.948683, 0.910473, 0.395289], - [0.947594, 0.917399, 0.410665], - [0.946809, 0.924168, 0.426373], - [0.946392, 0.930761, 0.442367], - [0.946403, 0.937159, 0.458592], - [0.946903, 0.943348, 0.474970], - [0.947937, 0.949318, 0.491426], - [0.949545, 0.955063, 0.507860], - [0.951740, 0.960587, 0.524203], - [0.954529, 0.965896, 0.540361], - [0.957896, 0.971003, 0.556275], - [0.961812, 0.975924, 0.571925], - [0.966249, 0.980678, 0.587206], - [0.971162, 0.985282, 0.602154], - [0.976511, 0.989753, 0.616760], - [0.982257, 0.994109, 0.631017], - [0.988362, 0.998364, 0.644924]] - -_plasma_data = [[0.050383, 0.029803, 0.527975], - [0.063536, 0.028426, 0.533124], - [0.075353, 0.027206, 0.538007], - [0.086222, 0.026125, 0.542658], - [0.096379, 0.025165, 0.547103], - [0.105980, 0.024309, 0.551368], - [0.115124, 0.023556, 0.555468], - [0.123903, 0.022878, 0.559423], - [0.132381, 0.022258, 0.563250], - [0.140603, 0.021687, 0.566959], - [0.148607, 0.021154, 0.570562], - [0.156421, 0.020651, 0.574065], - [0.164070, 0.020171, 0.577478], - [0.171574, 0.019706, 0.580806], - [0.178950, 0.019252, 0.584054], - [0.186213, 0.018803, 0.587228], - [0.193374, 0.018354, 0.590330], - [0.200445, 0.017902, 0.593364], - [0.207435, 0.017442, 0.596333], - [0.214350, 0.016973, 0.599239], - [0.221197, 0.016497, 0.602083], - [0.227983, 0.016007, 0.604867], - [0.234715, 0.015502, 0.607592], - [0.241396, 0.014979, 0.610259], - [0.248032, 0.014439, 0.612868], - [0.254627, 0.013882, 0.615419], - [0.261183, 0.013308, 0.617911], - [0.267703, 0.012716, 0.620346], - [0.274191, 0.012109, 0.622722], - [0.280648, 0.011488, 0.625038], - [0.287076, 0.010855, 0.627295], - [0.293478, 0.010213, 0.629490], - [0.299855, 0.009561, 0.631624], - [0.306210, 0.008902, 0.633694], - [0.312543, 0.008239, 0.635700], - [0.318856, 0.007576, 0.637640], - [0.325150, 0.006915, 0.639512], - [0.331426, 0.006261, 0.641316], - [0.337683, 0.005618, 0.643049], - [0.343925, 0.004991, 0.644710], - [0.350150, 0.004382, 0.646298], - [0.356359, 0.003798, 0.647810], - [0.362553, 0.003243, 0.649245], - [0.368733, 0.002724, 0.650601], - [0.374897, 0.002245, 0.651876], - [0.381047, 0.001814, 0.653068], - [0.387183, 0.001434, 0.654177], - [0.393304, 0.001114, 0.655199], - [0.399411, 0.000859, 0.656133], - [0.405503, 0.000678, 0.656977], - [0.411580, 0.000577, 0.657730], - [0.417642, 0.000564, 0.658390], - [0.423689, 0.000646, 0.658956], - [0.429719, 0.000831, 0.659425], - [0.435734, 0.001127, 0.659797], - [0.441732, 0.001540, 0.660069], - [0.447714, 0.002080, 0.660240], - [0.453677, 0.002755, 0.660310], - [0.459623, 0.003574, 0.660277], - [0.465550, 0.004545, 0.660139], - [0.471457, 0.005678, 0.659897], - [0.477344, 0.006980, 0.659549], - [0.483210, 0.008460, 0.659095], - [0.489055, 0.010127, 0.658534], - [0.494877, 0.011990, 0.657865], - [0.500678, 0.014055, 0.657088], - [0.506454, 0.016333, 0.656202], - [0.512206, 0.018833, 0.655209], - [0.517933, 0.021563, 0.654109], - [0.523633, 0.024532, 0.652901], - [0.529306, 0.027747, 0.651586], - [0.534952, 0.031217, 0.650165], - [0.540570, 0.034950, 0.648640], - [0.546157, 0.038954, 0.647010], - [0.551715, 0.043136, 0.645277], - [0.557243, 0.047331, 0.643443], - [0.562738, 0.051545, 0.641509], - [0.568201, 0.055778, 0.639477], - [0.573632, 0.060028, 0.637349], - [0.579029, 0.064296, 0.635126], - [0.584391, 0.068579, 0.632812], - [0.589719, 0.072878, 0.630408], - [0.595011, 0.077190, 0.627917], - [0.600266, 0.081516, 0.625342], - [0.605485, 0.085854, 0.622686], - [0.610667, 0.090204, 0.619951], - [0.615812, 0.094564, 0.617140], - [0.620919, 0.098934, 0.614257], - [0.625987, 0.103312, 0.611305], - [0.631017, 0.107699, 0.608287], - [0.636008, 0.112092, 0.605205], - [0.640959, 0.116492, 0.602065], - [0.645872, 0.120898, 0.598867], - [0.650746, 0.125309, 0.595617], - [0.655580, 0.129725, 0.592317], - [0.660374, 0.134144, 0.588971], - [0.665129, 0.138566, 0.585582], - [0.669845, 0.142992, 0.582154], - [0.674522, 0.147419, 0.578688], - [0.679160, 0.151848, 0.575189], - [0.683758, 0.156278, 0.571660], - [0.688318, 0.160709, 0.568103], - [0.692840, 0.165141, 0.564522], - [0.697324, 0.169573, 0.560919], - [0.701769, 0.174005, 0.557296], - [0.706178, 0.178437, 0.553657], - [0.710549, 0.182868, 0.550004], - [0.714883, 0.187299, 0.546338], - [0.719181, 0.191729, 0.542663], - [0.723444, 0.196158, 0.538981], - [0.727670, 0.200586, 0.535293], - [0.731862, 0.205013, 0.531601], - [0.736019, 0.209439, 0.527908], - [0.740143, 0.213864, 0.524216], - [0.744232, 0.218288, 0.520524], - [0.748289, 0.222711, 0.516834], - [0.752312, 0.227133, 0.513149], - [0.756304, 0.231555, 0.509468], - [0.760264, 0.235976, 0.505794], - [0.764193, 0.240396, 0.502126], - [0.768090, 0.244817, 0.498465], - [0.771958, 0.249237, 0.494813], - [0.775796, 0.253658, 0.491171], - [0.779604, 0.258078, 0.487539], - [0.783383, 0.262500, 0.483918], - [0.787133, 0.266922, 0.480307], - [0.790855, 0.271345, 0.476706], - [0.794549, 0.275770, 0.473117], - [0.798216, 0.280197, 0.469538], - [0.801855, 0.284626, 0.465971], - [0.805467, 0.289057, 0.462415], - [0.809052, 0.293491, 0.458870], - [0.812612, 0.297928, 0.455338], - [0.816144, 0.302368, 0.451816], - [0.819651, 0.306812, 0.448306], - [0.823132, 0.311261, 0.444806], - [0.826588, 0.315714, 0.441316], - [0.830018, 0.320172, 0.437836], - [0.833422, 0.324635, 0.434366], - [0.836801, 0.329105, 0.430905], - [0.840155, 0.333580, 0.427455], - [0.843484, 0.338062, 0.424013], - [0.846788, 0.342551, 0.420579], - [0.850066, 0.347048, 0.417153], - [0.853319, 0.351553, 0.413734], - [0.856547, 0.356066, 0.410322], - [0.859750, 0.360588, 0.406917], - [0.862927, 0.365119, 0.403519], - [0.866078, 0.369660, 0.400126], - [0.869203, 0.374212, 0.396738], - [0.872303, 0.378774, 0.393355], - [0.875376, 0.383347, 0.389976], - [0.878423, 0.387932, 0.386600], - [0.881443, 0.392529, 0.383229], - [0.884436, 0.397139, 0.379860], - [0.887402, 0.401762, 0.376494], - [0.890340, 0.406398, 0.373130], - [0.893250, 0.411048, 0.369768], - [0.896131, 0.415712, 0.366407], - [0.898984, 0.420392, 0.363047], - [0.901807, 0.425087, 0.359688], - [0.904601, 0.429797, 0.356329], - [0.907365, 0.434524, 0.352970], - [0.910098, 0.439268, 0.349610], - [0.912800, 0.444029, 0.346251], - [0.915471, 0.448807, 0.342890], - [0.918109, 0.453603, 0.339529], - [0.920714, 0.458417, 0.336166], - [0.923287, 0.463251, 0.332801], - [0.925825, 0.468103, 0.329435], - [0.928329, 0.472975, 0.326067], - [0.930798, 0.477867, 0.322697], - [0.933232, 0.482780, 0.319325], - [0.935630, 0.487712, 0.315952], - [0.937990, 0.492667, 0.312575], - [0.940313, 0.497642, 0.309197], - [0.942598, 0.502639, 0.305816], - [0.944844, 0.507658, 0.302433], - [0.947051, 0.512699, 0.299049], - [0.949217, 0.517763, 0.295662], - [0.951344, 0.522850, 0.292275], - [0.953428, 0.527960, 0.288883], - [0.955470, 0.533093, 0.285490], - [0.957469, 0.538250, 0.282096], - [0.959424, 0.543431, 0.278701], - [0.961336, 0.548636, 0.275305], - [0.963203, 0.553865, 0.271909], - [0.965024, 0.559118, 0.268513], - [0.966798, 0.564396, 0.265118], - [0.968526, 0.569700, 0.261721], - [0.970205, 0.575028, 0.258325], - [0.971835, 0.580382, 0.254931], - [0.973416, 0.585761, 0.251540], - [0.974947, 0.591165, 0.248151], - [0.976428, 0.596595, 0.244767], - [0.977856, 0.602051, 0.241387], - [0.979233, 0.607532, 0.238013], - [0.980556, 0.613039, 0.234646], - [0.981826, 0.618572, 0.231287], - [0.983041, 0.624131, 0.227937], - [0.984199, 0.629718, 0.224595], - [0.985301, 0.635330, 0.221265], - [0.986345, 0.640969, 0.217948], - [0.987332, 0.646633, 0.214648], - [0.988260, 0.652325, 0.211364], - [0.989128, 0.658043, 0.208100], - [0.989935, 0.663787, 0.204859], - [0.990681, 0.669558, 0.201642], - [0.991365, 0.675355, 0.198453], - [0.991985, 0.681179, 0.195295], - [0.992541, 0.687030, 0.192170], - [0.993032, 0.692907, 0.189084], - [0.993456, 0.698810, 0.186041], - [0.993814, 0.704741, 0.183043], - [0.994103, 0.710698, 0.180097], - [0.994324, 0.716681, 0.177208], - [0.994474, 0.722691, 0.174381], - [0.994553, 0.728728, 0.171622], - [0.994561, 0.734791, 0.168938], - [0.994495, 0.740880, 0.166335], - [0.994355, 0.746995, 0.163821], - [0.994141, 0.753137, 0.161404], - [0.993851, 0.759304, 0.159092], - [0.993482, 0.765499, 0.156891], - [0.993033, 0.771720, 0.154808], - [0.992505, 0.777967, 0.152855], - [0.991897, 0.784239, 0.151042], - [0.991209, 0.790537, 0.149377], - [0.990439, 0.796859, 0.147870], - [0.989587, 0.803205, 0.146529], - [0.988648, 0.809579, 0.145357], - [0.987621, 0.815978, 0.144363], - [0.986509, 0.822401, 0.143557], - [0.985314, 0.828846, 0.142945], - [0.984031, 0.835315, 0.142528], - [0.982653, 0.841812, 0.142303], - [0.981190, 0.848329, 0.142279], - [0.979644, 0.854866, 0.142453], - [0.977995, 0.861432, 0.142808], - [0.976265, 0.868016, 0.143351], - [0.974443, 0.874622, 0.144061], - [0.972530, 0.881250, 0.144923], - [0.970533, 0.887896, 0.145919], - [0.968443, 0.894564, 0.147014], - [0.966271, 0.901249, 0.148180], - [0.964021, 0.907950, 0.149370], - [0.961681, 0.914672, 0.150520], - [0.959276, 0.921407, 0.151566], - [0.956808, 0.928152, 0.152409], - [0.954287, 0.934908, 0.152921], - [0.951726, 0.941671, 0.152925], - [0.949151, 0.948435, 0.152178], - [0.946602, 0.955190, 0.150328], - [0.944152, 0.961916, 0.146861], - [0.941896, 0.968590, 0.140956], - [0.940015, 0.975158, 0.131326]] - -_viridis_data = [[0.267004, 0.004874, 0.329415], - [0.268510, 0.009605, 0.335427], - [0.269944, 0.014625, 0.341379], - [0.271305, 0.019942, 0.347269], - [0.272594, 0.025563, 0.353093], - [0.273809, 0.031497, 0.358853], - [0.274952, 0.037752, 0.364543], - [0.276022, 0.044167, 0.370164], - [0.277018, 0.050344, 0.375715], - [0.277941, 0.056324, 0.381191], - [0.278791, 0.062145, 0.386592], - [0.279566, 0.067836, 0.391917], - [0.280267, 0.073417, 0.397163], - [0.280894, 0.078907, 0.402329], - [0.281446, 0.084320, 0.407414], - [0.281924, 0.089666, 0.412415], - [0.282327, 0.094955, 0.417331], - [0.282656, 0.100196, 0.422160], - [0.282910, 0.105393, 0.426902], - [0.283091, 0.110553, 0.431554], - [0.283197, 0.115680, 0.436115], - [0.283229, 0.120777, 0.440584], - [0.283187, 0.125848, 0.444960], - [0.283072, 0.130895, 0.449241], - [0.282884, 0.135920, 0.453427], - [0.282623, 0.140926, 0.457517], - [0.282290, 0.145912, 0.461510], - [0.281887, 0.150881, 0.465405], - [0.281412, 0.155834, 0.469201], - [0.280868, 0.160771, 0.472899], - [0.280255, 0.165693, 0.476498], - [0.279574, 0.170599, 0.479997], - [0.278826, 0.175490, 0.483397], - [0.278012, 0.180367, 0.486697], - [0.277134, 0.185228, 0.489898], - [0.276194, 0.190074, 0.493001], - [0.275191, 0.194905, 0.496005], - [0.274128, 0.199721, 0.498911], - [0.273006, 0.204520, 0.501721], - [0.271828, 0.209303, 0.504434], - [0.270595, 0.214069, 0.507052], - [0.269308, 0.218818, 0.509577], - [0.267968, 0.223549, 0.512008], - [0.266580, 0.228262, 0.514349], - [0.265145, 0.232956, 0.516599], - [0.263663, 0.237631, 0.518762], - [0.262138, 0.242286, 0.520837], - [0.260571, 0.246922, 0.522828], - [0.258965, 0.251537, 0.524736], - [0.257322, 0.256130, 0.526563], - [0.255645, 0.260703, 0.528312], - [0.253935, 0.265254, 0.529983], - [0.252194, 0.269783, 0.531579], - [0.250425, 0.274290, 0.533103], - [0.248629, 0.278775, 0.534556], - [0.246811, 0.283237, 0.535941], - [0.244972, 0.287675, 0.537260], - [0.243113, 0.292092, 0.538516], - [0.241237, 0.296485, 0.539709], - [0.239346, 0.300855, 0.540844], - [0.237441, 0.305202, 0.541921], - [0.235526, 0.309527, 0.542944], - [0.233603, 0.313828, 0.543914], - [0.231674, 0.318106, 0.544834], - [0.229739, 0.322361, 0.545706], - [0.227802, 0.326594, 0.546532], - [0.225863, 0.330805, 0.547314], - [0.223925, 0.334994, 0.548053], - [0.221989, 0.339161, 0.548752], - [0.220057, 0.343307, 0.549413], - [0.218130, 0.347432, 0.550038], - [0.216210, 0.351535, 0.550627], - [0.214298, 0.355619, 0.551184], - [0.212395, 0.359683, 0.551710], - [0.210503, 0.363727, 0.552206], - [0.208623, 0.367752, 0.552675], - [0.206756, 0.371758, 0.553117], - [0.204903, 0.375746, 0.553533], - [0.203063, 0.379716, 0.553925], - [0.201239, 0.383670, 0.554294], - [0.199430, 0.387607, 0.554642], - [0.197636, 0.391528, 0.554969], - [0.195860, 0.395433, 0.555276], - [0.194100, 0.399323, 0.555565], - [0.192357, 0.403199, 0.555836], - [0.190631, 0.407061, 0.556089], - [0.188923, 0.410910, 0.556326], - [0.187231, 0.414746, 0.556547], - [0.185556, 0.418570, 0.556753], - [0.183898, 0.422383, 0.556944], - [0.182256, 0.426184, 0.557120], - [0.180629, 0.429975, 0.557282], - [0.179019, 0.433756, 0.557430], - [0.177423, 0.437527, 0.557565], - [0.175841, 0.441290, 0.557685], - [0.174274, 0.445044, 0.557792], - [0.172719, 0.448791, 0.557885], - [0.171176, 0.452530, 0.557965], - [0.169646, 0.456262, 0.558030], - [0.168126, 0.459988, 0.558082], - [0.166617, 0.463708, 0.558119], - [0.165117, 0.467423, 0.558141], - [0.163625, 0.471133, 0.558148], - [0.162142, 0.474838, 0.558140], - [0.160665, 0.478540, 0.558115], - [0.159194, 0.482237, 0.558073], - [0.157729, 0.485932, 0.558013], - [0.156270, 0.489624, 0.557936], - [0.154815, 0.493313, 0.557840], - [0.153364, 0.497000, 0.557724], - [0.151918, 0.500685, 0.557587], - [0.150476, 0.504369, 0.557430], - [0.149039, 0.508051, 0.557250], - [0.147607, 0.511733, 0.557049], - [0.146180, 0.515413, 0.556823], - [0.144759, 0.519093, 0.556572], - [0.143343, 0.522773, 0.556295], - [0.141935, 0.526453, 0.555991], - [0.140536, 0.530132, 0.555659], - [0.139147, 0.533812, 0.555298], - [0.137770, 0.537492, 0.554906], - [0.136408, 0.541173, 0.554483], - [0.135066, 0.544853, 0.554029], - [0.133743, 0.548535, 0.553541], - [0.132444, 0.552216, 0.553018], - [0.131172, 0.555899, 0.552459], - [0.129933, 0.559582, 0.551864], - [0.128729, 0.563265, 0.551229], - [0.127568, 0.566949, 0.550556], - [0.126453, 0.570633, 0.549841], - [0.125394, 0.574318, 0.549086], - [0.124395, 0.578002, 0.548287], - [0.123463, 0.581687, 0.547445], - [0.122606, 0.585371, 0.546557], - [0.121831, 0.589055, 0.545623], - [0.121148, 0.592739, 0.544641], - [0.120565, 0.596422, 0.543611], - [0.120092, 0.600104, 0.542530], - [0.119738, 0.603785, 0.541400], - [0.119512, 0.607464, 0.540218], - [0.119423, 0.611141, 0.538982], - [0.119483, 0.614817, 0.537692], - [0.119699, 0.618490, 0.536347], - [0.120081, 0.622161, 0.534946], - [0.120638, 0.625828, 0.533488], - [0.121380, 0.629492, 0.531973], - [0.122312, 0.633153, 0.530398], - [0.123444, 0.636809, 0.528763], - [0.124780, 0.640461, 0.527068], - [0.126326, 0.644107, 0.525311], - [0.128087, 0.647749, 0.523491], - [0.130067, 0.651384, 0.521608], - [0.132268, 0.655014, 0.519661], - [0.134692, 0.658636, 0.517649], - [0.137339, 0.662252, 0.515571], - [0.140210, 0.665859, 0.513427], - [0.143303, 0.669459, 0.511215], - [0.146616, 0.673050, 0.508936], - [0.150148, 0.676631, 0.506589], - [0.153894, 0.680203, 0.504172], - [0.157851, 0.683765, 0.501686], - [0.162016, 0.687316, 0.499129], - [0.166383, 0.690856, 0.496502], - [0.170948, 0.694384, 0.493803], - [0.175707, 0.697900, 0.491033], - [0.180653, 0.701402, 0.488189], - [0.185783, 0.704891, 0.485273], - [0.191090, 0.708366, 0.482284], - [0.196571, 0.711827, 0.479221], - [0.202219, 0.715272, 0.476084], - [0.208030, 0.718701, 0.472873], - [0.214000, 0.722114, 0.469588], - [0.220124, 0.725509, 0.466226], - [0.226397, 0.728888, 0.462789], - [0.232815, 0.732247, 0.459277], - [0.239374, 0.735588, 0.455688], - [0.246070, 0.738910, 0.452024], - [0.252899, 0.742211, 0.448284], - [0.259857, 0.745492, 0.444467], - [0.266941, 0.748751, 0.440573], - [0.274149, 0.751988, 0.436601], - [0.281477, 0.755203, 0.432552], - [0.288921, 0.758394, 0.428426], - [0.296479, 0.761561, 0.424223], - [0.304148, 0.764704, 0.419943], - [0.311925, 0.767822, 0.415586], - [0.319809, 0.770914, 0.411152], - [0.327796, 0.773980, 0.406640], - [0.335885, 0.777018, 0.402049], - [0.344074, 0.780029, 0.397381], - [0.352360, 0.783011, 0.392636], - [0.360741, 0.785964, 0.387814], - [0.369214, 0.788888, 0.382914], - [0.377779, 0.791781, 0.377939], - [0.386433, 0.794644, 0.372886], - [0.395174, 0.797475, 0.367757], - [0.404001, 0.800275, 0.362552], - [0.412913, 0.803041, 0.357269], - [0.421908, 0.805774, 0.351910], - [0.430983, 0.808473, 0.346476], - [0.440137, 0.811138, 0.340967], - [0.449368, 0.813768, 0.335384], - [0.458674, 0.816363, 0.329727], - [0.468053, 0.818921, 0.323998], - [0.477504, 0.821444, 0.318195], - [0.487026, 0.823929, 0.312321], - [0.496615, 0.826376, 0.306377], - [0.506271, 0.828786, 0.300362], - [0.515992, 0.831158, 0.294279], - [0.525776, 0.833491, 0.288127], - [0.535621, 0.835785, 0.281908], - [0.545524, 0.838039, 0.275626], - [0.555484, 0.840254, 0.269281], - [0.565498, 0.842430, 0.262877], - [0.575563, 0.844566, 0.256415], - [0.585678, 0.846661, 0.249897], - [0.595839, 0.848717, 0.243329], - [0.606045, 0.850733, 0.236712], - [0.616293, 0.852709, 0.230052], - [0.626579, 0.854645, 0.223353], - [0.636902, 0.856542, 0.216620], - [0.647257, 0.858400, 0.209861], - [0.657642, 0.860219, 0.203082], - [0.668054, 0.861999, 0.196293], - [0.678489, 0.863742, 0.189503], - [0.688944, 0.865448, 0.182725], - [0.699415, 0.867117, 0.175971], - [0.709898, 0.868751, 0.169257], - [0.720391, 0.870350, 0.162603], - [0.730889, 0.871916, 0.156029], - [0.741388, 0.873449, 0.149561], - [0.751884, 0.874951, 0.143228], - [0.762373, 0.876424, 0.137064], - [0.772852, 0.877868, 0.131109], - [0.783315, 0.879285, 0.125405], - [0.793760, 0.880678, 0.120005], - [0.804182, 0.882046, 0.114965], - [0.814576, 0.883393, 0.110347], - [0.824940, 0.884720, 0.106217], - [0.835270, 0.886029, 0.102646], - [0.845561, 0.887322, 0.099702], - [0.855810, 0.888601, 0.097452], - [0.866013, 0.889868, 0.095953], - [0.876168, 0.891125, 0.095250], - [0.886271, 0.892374, 0.095374], - [0.896320, 0.893616, 0.096335], - [0.906311, 0.894855, 0.098125], - [0.916242, 0.896091, 0.100717], - [0.926106, 0.897330, 0.104071], - [0.935904, 0.898570, 0.108131], - [0.945636, 0.899815, 0.112838], - [0.955300, 0.901065, 0.118128], - [0.964894, 0.902323, 0.123941], - [0.974417, 0.903590, 0.130215], - [0.983868, 0.904867, 0.136897], - [0.993248, 0.906157, 0.143936]] - -_cividis_data = [[0.000000, 0.135112, 0.304751], - [0.000000, 0.138068, 0.311105], - [0.000000, 0.141013, 0.317579], - [0.000000, 0.143951, 0.323982], - [0.000000, 0.146877, 0.330479], - [0.000000, 0.149791, 0.337065], - [0.000000, 0.152673, 0.343704], - [0.000000, 0.155377, 0.350500], - [0.000000, 0.157932, 0.357521], - [0.000000, 0.160495, 0.364534], - [0.000000, 0.163058, 0.371608], - [0.000000, 0.165621, 0.378769], - [0.000000, 0.168204, 0.385902], - [0.000000, 0.170800, 0.393100], - [0.000000, 0.173420, 0.400353], - [0.000000, 0.176082, 0.407577], - [0.000000, 0.178802, 0.414764], - [0.000000, 0.181610, 0.421859], - [0.000000, 0.184550, 0.428802], - [0.000000, 0.186915, 0.435532], - [0.000000, 0.188769, 0.439563], - [0.000000, 0.190950, 0.441085], - [0.000000, 0.193366, 0.441561], - [0.003602, 0.195911, 0.441564], - [0.017852, 0.198528, 0.441248], - [0.032110, 0.201199, 0.440785], - [0.046205, 0.203903, 0.440196], - [0.058378, 0.206629, 0.439531], - [0.068968, 0.209372, 0.438863], - [0.078624, 0.212122, 0.438105], - [0.087465, 0.214879, 0.437342], - [0.095645, 0.217643, 0.436593], - [0.103401, 0.220406, 0.435790], - [0.110658, 0.223170, 0.435067], - [0.117612, 0.225935, 0.434308], - [0.124291, 0.228697, 0.433547], - [0.130669, 0.231458, 0.432840], - [0.136830, 0.234216, 0.432148], - [0.142852, 0.236972, 0.431404], - [0.148638, 0.239724, 0.430752], - [0.154261, 0.242475, 0.430120], - [0.159733, 0.245221, 0.429528], - [0.165113, 0.247965, 0.428908], - [0.170362, 0.250707, 0.428325], - [0.175490, 0.253444, 0.427790], - [0.180503, 0.256180, 0.427299], - [0.185453, 0.258914, 0.426788], - [0.190303, 0.261644, 0.426329], - [0.195057, 0.264372, 0.425924], - [0.199764, 0.267099, 0.425497], - [0.204385, 0.269823, 0.425126], - [0.208926, 0.272546, 0.424809], - [0.213431, 0.275266, 0.424480], - [0.217863, 0.277985, 0.424206], - [0.222264, 0.280702, 0.423914], - [0.226598, 0.283419, 0.423678], - [0.230871, 0.286134, 0.423498], - [0.235120, 0.288848, 0.423304], - [0.239312, 0.291562, 0.423167], - [0.243485, 0.294274, 0.423014], - [0.247605, 0.296986, 0.422917], - [0.251675, 0.299698, 0.422873], - [0.255731, 0.302409, 0.422814], - [0.259740, 0.305120, 0.422810], - [0.263738, 0.307831, 0.422789], - [0.267693, 0.310542, 0.422821], - [0.271639, 0.313253, 0.422837], - [0.275513, 0.315965, 0.422979], - [0.279411, 0.318677, 0.423031], - [0.283240, 0.321390, 0.423211], - [0.287065, 0.324103, 0.423373], - [0.290884, 0.326816, 0.423517], - [0.294669, 0.329531, 0.423716], - [0.298421, 0.332247, 0.423973], - [0.302169, 0.334963, 0.424213], - [0.305886, 0.337681, 0.424512], - [0.309601, 0.340399, 0.424790], - [0.313287, 0.343120, 0.425120], - [0.316941, 0.345842, 0.425512], - [0.320595, 0.348565, 0.425889], - [0.324250, 0.351289, 0.426250], - [0.327875, 0.354016, 0.426670], - [0.331474, 0.356744, 0.427144], - [0.335073, 0.359474, 0.427605], - [0.338673, 0.362206, 0.428053], - [0.342246, 0.364939, 0.428559], - [0.345793, 0.367676, 0.429127], - [0.349341, 0.370414, 0.429685], - [0.352892, 0.373153, 0.430226], - [0.356418, 0.375896, 0.430823], - [0.359916, 0.378641, 0.431501], - [0.363446, 0.381388, 0.432075], - [0.366923, 0.384139, 0.432796], - [0.370430, 0.386890, 0.433428], - [0.373884, 0.389646, 0.434209], - [0.377371, 0.392404, 0.434890], - [0.380830, 0.395164, 0.435653], - [0.384268, 0.397928, 0.436475], - [0.387705, 0.400694, 0.437305], - [0.391151, 0.403464, 0.438096], - [0.394568, 0.406236, 0.438986], - [0.397991, 0.409011, 0.439848], - [0.401418, 0.411790, 0.440708], - [0.404820, 0.414572, 0.441642], - [0.408226, 0.417357, 0.442570], - [0.411607, 0.420145, 0.443577], - [0.414992, 0.422937, 0.444578], - [0.418383, 0.425733, 0.445560], - [0.421748, 0.428531, 0.446640], - [0.425120, 0.431334, 0.447692], - [0.428462, 0.434140, 0.448864], - [0.431817, 0.436950, 0.449982], - [0.435168, 0.439763, 0.451134], - [0.438504, 0.442580, 0.452341], - [0.441810, 0.445402, 0.453659], - [0.445148, 0.448226, 0.454885], - [0.448447, 0.451053, 0.456264], - [0.451759, 0.453887, 0.457582], - [0.455072, 0.456718, 0.458976], - [0.458366, 0.459552, 0.460457], - [0.461616, 0.462405, 0.461969], - [0.464947, 0.465241, 0.463395], - [0.468254, 0.468083, 0.464908], - [0.471501, 0.470960, 0.466357], - [0.474812, 0.473832, 0.467681], - [0.478186, 0.476699, 0.468845], - [0.481622, 0.479573, 0.469767], - [0.485141, 0.482451, 0.470384], - [0.488697, 0.485318, 0.471008], - [0.492278, 0.488198, 0.471453], - [0.495913, 0.491076, 0.471751], - [0.499552, 0.493960, 0.472032], - [0.503185, 0.496851, 0.472305], - [0.506866, 0.499743, 0.472432], - [0.510540, 0.502643, 0.472550], - [0.514226, 0.505546, 0.472640], - [0.517920, 0.508454, 0.472707], - [0.521643, 0.511367, 0.472639], - [0.525348, 0.514285, 0.472660], - [0.529086, 0.517207, 0.472543], - [0.532829, 0.520135, 0.472401], - [0.536553, 0.523067, 0.472352], - [0.540307, 0.526005, 0.472163], - [0.544069, 0.528948, 0.471947], - [0.547840, 0.531895, 0.471704], - [0.551612, 0.534849, 0.471439], - [0.555393, 0.537807, 0.471147], - [0.559181, 0.540771, 0.470829], - [0.562972, 0.543741, 0.470488], - [0.566802, 0.546715, 0.469988], - [0.570607, 0.549695, 0.469593], - [0.574417, 0.552682, 0.469172], - [0.578236, 0.555673, 0.468724], - [0.582087, 0.558670, 0.468118], - [0.585916, 0.561674, 0.467618], - [0.589753, 0.564682, 0.467090], - [0.593622, 0.567697, 0.466401], - [0.597469, 0.570718, 0.465821], - [0.601354, 0.573743, 0.465074], - [0.605211, 0.576777, 0.464441], - [0.609105, 0.579816, 0.463638], - [0.612977, 0.582861, 0.462950], - [0.616852, 0.585913, 0.462237], - [0.620765, 0.588970, 0.461351], - [0.624654, 0.592034, 0.460583], - [0.628576, 0.595104, 0.459641], - [0.632506, 0.598180, 0.458668], - [0.636412, 0.601264, 0.457818], - [0.640352, 0.604354, 0.456791], - [0.644270, 0.607450, 0.455886], - [0.648222, 0.610553, 0.454801], - [0.652178, 0.613664, 0.453689], - [0.656114, 0.616780, 0.452702], - [0.660082, 0.619904, 0.451534], - [0.664055, 0.623034, 0.450338], - [0.668008, 0.626171, 0.449270], - [0.671991, 0.629316, 0.448018], - [0.675981, 0.632468, 0.446736], - [0.679979, 0.635626, 0.445424], - [0.683950, 0.638793, 0.444251], - [0.687957, 0.641966, 0.442886], - [0.691971, 0.645145, 0.441491], - [0.695985, 0.648334, 0.440072], - [0.700008, 0.651529, 0.438624], - [0.704037, 0.654731, 0.437147], - [0.708067, 0.657942, 0.435647], - [0.712105, 0.661160, 0.434117], - [0.716177, 0.664384, 0.432386], - [0.720222, 0.667618, 0.430805], - [0.724274, 0.670859, 0.429194], - [0.728334, 0.674107, 0.427554], - [0.732422, 0.677364, 0.425717], - [0.736488, 0.680629, 0.424028], - [0.740589, 0.683900, 0.422131], - [0.744664, 0.687181, 0.420393], - [0.748772, 0.690470, 0.418448], - [0.752886, 0.693766, 0.416472], - [0.756975, 0.697071, 0.414659], - [0.761096, 0.700384, 0.412638], - [0.765223, 0.703705, 0.410587], - [0.769353, 0.707035, 0.408516], - [0.773486, 0.710373, 0.406422], - [0.777651, 0.713719, 0.404112], - [0.781795, 0.717074, 0.401966], - [0.785965, 0.720438, 0.399613], - [0.790116, 0.723810, 0.397423], - [0.794298, 0.727190, 0.395016], - [0.798480, 0.730580, 0.392597], - [0.802667, 0.733978, 0.390153], - [0.806859, 0.737385, 0.387684], - [0.811054, 0.740801, 0.385198], - [0.815274, 0.744226, 0.382504], - [0.819499, 0.747659, 0.379785], - [0.823729, 0.751101, 0.377043], - [0.827959, 0.754553, 0.374292], - [0.832192, 0.758014, 0.371529], - [0.836429, 0.761483, 0.368747], - [0.840693, 0.764962, 0.365746], - [0.844957, 0.768450, 0.362741], - [0.849223, 0.771947, 0.359729], - [0.853515, 0.775454, 0.356500], - [0.857809, 0.778969, 0.353259], - [0.862105, 0.782494, 0.350011], - [0.866421, 0.786028, 0.346571], - [0.870717, 0.789572, 0.343333], - [0.875057, 0.793125, 0.339685], - [0.879378, 0.796687, 0.336241], - [0.883720, 0.800258, 0.332599], - [0.888081, 0.803839, 0.328770], - [0.892440, 0.807430, 0.324968], - [0.896818, 0.811030, 0.320982], - [0.901195, 0.814639, 0.317021], - [0.905589, 0.818257, 0.312889], - [0.910000, 0.821885, 0.308594], - [0.914407, 0.825522, 0.304348], - [0.918828, 0.829168, 0.299960], - [0.923279, 0.832822, 0.295244], - [0.927724, 0.836486, 0.290611], - [0.932180, 0.840159, 0.285880], - [0.936660, 0.843841, 0.280876], - [0.941147, 0.847530, 0.275815], - [0.945654, 0.851228, 0.270532], - [0.950178, 0.854933, 0.265085], - [0.954725, 0.858646, 0.259365], - [0.959284, 0.862365, 0.253563], - [0.963872, 0.866089, 0.247445], - [0.968469, 0.869819, 0.241310], - [0.973114, 0.873550, 0.234677], - [0.977780, 0.877281, 0.227954], - [0.982497, 0.881008, 0.220878], - [0.987293, 0.884718, 0.213336], - [0.992218, 0.888385, 0.205468], - [0.994847, 0.892954, 0.203445], - [0.995249, 0.898384, 0.207561], - [0.995503, 0.903866, 0.212370], - [0.995737, 0.909344, 0.217772]] - -_twilight_data = [ - [0.88575015840754434, 0.85000924943067835, 0.8879736506427196], - [0.88378520195539056, 0.85072940540310626, 0.88723222096949894], - [0.88172231059285788, 0.85127594077653468, 0.88638056925514819], - [0.8795410528270573, 0.85165675407495722, 0.8854143767924102], - [0.87724880858965482, 0.85187028338870274, 0.88434120381311432], - [0.87485347508575972, 0.85191526123023187, 0.88316926967613829], - [0.87233134085124076, 0.85180165478080894, 0.88189704355001619], - [0.86970474853509816, 0.85152403004797894, 0.88053883390003362], - [0.86696015505333579, 0.8510896085314068, 0.87909766977173343], - [0.86408985081463996, 0.85050391167507788, 0.87757925784892632], - [0.86110245436899846, 0.84976754857001258, 0.87599242923439569], - [0.85798259245670372, 0.84888934810281835, 0.87434038553446281], - [0.85472593189256985, 0.84787488124672816, 0.8726282980930582], - [0.85133714570857189, 0.84672735796116472, 0.87086081657350445], - [0.84780710702577922, 0.8454546229209523, 0.86904036783694438], - [0.8441261828674842, 0.84406482711037389, 0.86716973322690072], - [0.84030420805957784, 0.8425605950855084, 0.865250882410458], - [0.83634031809191178, 0.84094796518951942, 0.86328528001070159], - [0.83222705712934408, 0.83923490627754482, 0.86127563500427884], - [0.82796894316013536, 0.83742600751395202, 0.85922399451306786], - [0.82357429680252847, 0.83552487764795436, 0.85713191328514948], - [0.81904654677937527, 0.8335364929949034, 0.85500206287010105], - [0.81438982121143089, 0.83146558694197847, 0.85283759062147024], - [0.8095999819094809, 0.82931896673505456, 0.85064441601050367], - [0.80469164429814577, 0.82709838780560663, 0.84842449296974021], - [0.79967075421267997, 0.82480781812080928, 0.84618210029578533], - [0.79454305089231114, 0.82245116226304615, 0.84392184786827984], - [0.78931445564608915, 0.82003213188702007, 0.8416486380471222], - [0.78399101042764918, 0.81755426400533426, 0.83936747464036732], - [0.77857892008227592, 0.81502089378742548, 0.8370834463093898], - [0.77308416590170936, 0.81243524735466011, 0.83480172950579679], - [0.76751108504417864, 0.8098007598713145, 0.83252816638059668], - [0.76186907937980286, 0.80711949387647486, 0.830266486168872], - [0.75616443584381976, 0.80439408733477935, 0.82802138994719998], - [0.75040346765406696, 0.80162699008965321, 0.82579737851082424], - [0.74459247771890169, 0.79882047719583249, 0.82359867586156521], - [0.73873771700494939, 0.79597665735031009, 0.82142922780433014], - [0.73284543645523459, 0.79309746468844067, 0.81929263384230377], - [0.72692177512829703, 0.7901846863592763, 0.81719217466726379], - [0.72097280665536778, 0.78723995923452639, 0.81513073920879264], - [0.71500403076252128, 0.78426487091581187, 0.81311116559949914], - [0.70902078134539304, 0.78126088716070907, 0.81113591855117928], - [0.7030297722540817, 0.77822904973358131, 0.80920618848056969], - [0.6970365443886174, 0.77517050008066057, 0.80732335380063447], - [0.69104641009309098, 0.77208629460678091, 0.80548841690679074], - [0.68506446154395928, 0.7689774029354699, 0.80370206267176914], - [0.67909554499882152, 0.76584472131395898, 0.8019646617300199], - [0.67314422559426212, 0.76268908733890484, 0.80027628545809526], - [0.66721479803752815, 0.7595112803730375, 0.79863674654537764], - [0.6613112930078745, 0.75631202708719025, 0.7970456043491897], - [0.65543692326454717, 0.75309208756768431, 0.79550271129031047], - [0.64959573004253479, 0.74985201221941766, 0.79400674021499107], - [0.6437910831099849, 0.7465923800833657, 0.79255653201306053], - [0.63802586828545982, 0.74331376714033193, 0.79115100459573173], - [0.6323027138710603, 0.74001672160131404, 0.78978892762640429], - [0.62662402022604591, 0.73670175403699445, 0.78846901316334561], - [0.62099193064817548, 0.73336934798923203, 0.78718994624696581], - [0.61540846411770478, 0.73001995232739691, 0.78595022706750484], - [0.60987543176093062, 0.72665398759758293, 0.78474835732694714], - [0.60439434200274855, 0.7232718614323369, 0.78358295593535587], - [0.5989665814482068, 0.71987394892246725, 0.78245259899346642], - [0.59359335696837223, 0.7164606049658685, 0.78135588237640097], - [0.58827579780555495, 0.71303214646458135, 0.78029141405636515], - [0.58301487036932409, 0.70958887676997473, 0.77925781820476592], - [0.5778116438998202, 0.70613106157153982, 0.77825345121025524], - [0.5726668948158774, 0.7026589535425779, 0.77727702680911992], - [0.56758117853861967, 0.69917279302646274, 0.77632748534275298], - [0.56255515357219343, 0.69567278381629649, 0.77540359142309845], - [0.55758940419605174, 0.69215911458254054, 0.7745041337932782], - [0.55268450589347129, 0.68863194515166382, 0.7736279426902245], - [0.54784098153018634, 0.68509142218509878, 0.77277386473440868], - [0.54305932424018233, 0.68153767253065878, 0.77194079697835083], - [0.53834015575176275, 0.67797081129095405, 0.77112734439057717], - [0.53368389147728401, 0.67439093705212727, 0.7703325054879735], - [0.529090861832473, 0.67079812302806219, 0.76955552292313134], - [0.52456151470593582, 0.66719242996142225, 0.76879541714230948], - [0.52009627392235558, 0.66357391434030388, 0.76805119403344102], - [0.5156955988596057, 0.65994260812897998, 0.76732191489596169], - [0.51135992541601927, 0.65629853981831865, 0.76660663780645333], - [0.50708969576451657, 0.65264172403146448, 0.76590445660835849], - [0.5028853540415561, 0.64897216734095264, 0.76521446718174913], - [0.49874733661356069, 0.6452898684900934, 0.76453578734180083], - [0.4946761847863938, 0.64159484119504429, 0.76386719002130909], - [0.49067224938561221, 0.63788704858847078, 0.76320812763163837], - [0.4867359599430568, 0.63416646251100506, 0.76255780085924041], - [0.4828677867260272, 0.6304330455306234, 0.76191537149895305], - [0.47906816236197386, 0.62668676251860134, 0.76128000375662419], - [0.47533752394906287, 0.62292757283835809, 0.76065085571817748], - [0.47167629518877091, 0.61915543242884641, 0.76002709227883047], - [0.46808490970531597, 0.61537028695790286, 0.75940789891092741], - [0.46456376716303932, 0.61157208822864151, 0.75879242623025811], - [0.46111326647023881, 0.607760777169989, 0.75817986436807139], - [0.45773377230160567, 0.60393630046586455, 0.75756936901859162], - [0.45442563977552913, 0.60009859503858665, 0.75696013660606487], - [0.45118918687617743, 0.59624762051353541, 0.75635120643246645], - [0.44802470933589172, 0.59238331452146575, 0.75574176474107924], - [0.44493246854215379, 0.5885055998308617, 0.7551311041857901], - [0.44191271766696399, 0.58461441100175571, 0.75451838884410671], - [0.43896563958048396, 0.58070969241098491, 0.75390276208285945], - [0.43609138958356369, 0.57679137998186081, 0.7532834105961016], - [0.43329008867358393, 0.57285941625606673, 0.75265946532566674], - [0.43056179073057571, 0.56891374572457176, 0.75203008099312696], - [0.42790652284925834, 0.5649543060909209, 0.75139443521914839], - [0.42532423665011354, 0.56098104959950301, 0.75075164989005116], - [0.42281485675772662, 0.55699392126996583, 0.75010086988227642], - [0.42037822361396326, 0.55299287158108168, 0.7494412559451894], - [0.41801414079233629, 0.54897785421888889, 0.74877193167001121], - [0.4157223260454232, 0.54494882715350401, 0.74809204459000522], - [0.41350245743314729, 0.54090574771098476, 0.74740073297543086], - [0.41135414697304568, 0.53684857765005933, 0.74669712855065784], - [0.4092768899914751, 0.53277730177130322, 0.74598030635707824], - [0.40727018694219069, 0.52869188011057411, 0.74524942637581271], - [0.40533343789303178, 0.52459228174983119, 0.74450365836708132], - [0.40346600333905397, 0.52047847653840029, 0.74374215223567086], - [0.40166714010896104, 0.51635044969688759, 0.7429640345324835], - [0.39993606933454834, 0.51220818143218516, 0.74216844571317986], - [0.3982719152586337, 0.50805166539276136, 0.74135450918099721], - [0.39667374905665609, 0.50388089053847973, 0.74052138580516735], - [0.39514058808207631, 0.49969585326377758, 0.73966820211715711], - [0.39367135736822567, 0.49549655777451179, 0.738794102296364], - [0.39226494876209317, 0.49128300332899261, 0.73789824784475078], - [0.39092017571994903, 0.48705520251223039, 0.73697977133881254], - [0.38963580160340855, 0.48281316715123496, 0.73603782546932739], - [0.38841053300842432, 0.47855691131792805, 0.73507157641157261], - [0.38724301459330251, 0.47428645933635388, 0.73408016787854391], - [0.38613184178892102, 0.4700018340988123, 0.7330627749243106], - [0.38507556793651387, 0.46570306719930193, 0.73201854033690505], - [0.38407269378943537, 0.46139018782416635, 0.73094665432902683], - [0.38312168084402748, 0.45706323581407199, 0.72984626791353258], - [0.38222094988570376, 0.45272225034283325, 0.72871656144003782], - [0.38136887930454161, 0.44836727669277859, 0.72755671317141346], - [0.38056380696565623, 0.44399837208633719, 0.72636587045135315], - [0.37980403744848751, 0.43961558821222629, 0.72514323778761092], - [0.37908789283110761, 0.43521897612544935, 0.72388798691323131], - [0.378413635091359, 0.43080859411413064, 0.72259931993061044], - [0.37777949753513729, 0.4263845142616835, 0.72127639993530235], - [0.37718371844251231, 0.42194680223454828, 0.71991841524475775], - [0.37662448930806297, 0.41749553747893614, 0.71852454736176108], - [0.37610001286385814, 0.41303079952477062, 0.71709396919920232], - [0.37560846919442398, 0.40855267638072096, 0.71562585091587549], - [0.37514802505380473, 0.4040612609993941, 0.7141193695725726], - [0.37471686019302231, 0.3995566498711684, 0.71257368516500463], - [0.37431313199312338, 0.39503894828283309, 0.71098796522377461], - [0.37393499330475782, 0.39050827529375831, 0.70936134293478448], - [0.3735806215098284, 0.38596474386057539, 0.70769297607310577], - [0.37324816143326384, 0.38140848555753937, 0.70598200974806036], - [0.37293578646665032, 0.37683963835219841, 0.70422755780589941], - [0.37264166757849604, 0.37225835004836849, 0.7024287314570723], - [0.37236397858465387, 0.36766477862108266, 0.70058463496520773], - [0.37210089702443822, 0.36305909736982378, 0.69869434615073722], - [0.3718506155898596, 0.35844148285875221, 0.69675695810256544], - [0.37161133234400479, 0.3538121372967869, 0.69477149919380887], - [0.37138124223736607, 0.34917126878479027, 0.69273703471928827], - [0.37115856636209105, 0.34451911410230168, 0.69065253586464992], - [0.37094151551337329, 0.33985591488818123, 0.68851703379505125], - [0.37072833279422668, 0.33518193808489577, 0.68632948169606767], - [0.37051738634484427, 0.33049741244307851, 0.68408888788857214], - [0.37030682071842685, 0.32580269697872455, 0.68179411684486679], - [0.37009487130772695, 0.3210981375964933, 0.67944405399056851], - [0.36987980329025361, 0.31638410101153364, 0.67703755438090574], - [0.36965987626565955, 0.31166098762951971, 0.67457344743419545], - [0.36943334591276228, 0.30692923551862339, 0.67205052849120617], - [0.36919847837592484, 0.30218932176507068, 0.66946754331614522], - [0.36895355306596778, 0.29744175492366276, 0.66682322089824264], - [0.36869682231895268, 0.29268709856150099, 0.66411625298236909], - [0.36842655638020444, 0.28792596437778462, 0.66134526910944602], - [0.36814101479899719, 0.28315901221182987, 0.65850888806972308], - [0.36783843696531082, 0.27838697181297761, 0.65560566838453704], - [0.36751707094367697, 0.27361063317090978, 0.65263411711618635], - [0.36717513650699446, 0.26883085667326956, 0.64959272297892245], - [0.36681085540107988, 0.26404857724525643, 0.64647991652908243], - [0.36642243251550632, 0.25926481158628106, 0.64329409140765537], - [0.36600853966739794, 0.25448043878086224, 0.64003361803368586], - [0.36556698373538982, 0.24969683475296395, 0.63669675187488584], - [0.36509579845886808, 0.24491536803550484, 0.63328173520055586], - [0.36459308890125008, 0.24013747024823828, 0.62978680155026101], - [0.36405693022088509, 0.23536470386204195, 0.62621013451953023], - [0.36348537610385145, 0.23059876218396419, 0.62254988622392882], - [0.36287643560041027, 0.22584149293287031, 0.61880417410823019], - [0.36222809558295926, 0.22109488427338303, 0.61497112346096128], - [0.36153829010998356, 0.21636111429594002, 0.61104880679640927], - [0.36080493826624654, 0.21164251793458128, 0.60703532172064711], - [0.36002681809096376, 0.20694122817889948, 0.60292845431916875], - [0.35920088560930186, 0.20226037920758122, 0.5987265295935138], - [0.35832489966617809, 0.197602942459778, 0.59442768517501066], - [0.35739663292915563, 0.19297208197842461, 0.59003011251063131], - [0.35641381143126327, 0.18837119869242164, 0.5855320765920552], - [0.35537415306906722, 0.18380392577704466, 0.58093191431832802], - [0.35427534960663759, 0.17927413271618647, 0.57622809660668717], - [0.35311574421123737, 0.17478570377561287, 0.57141871523555288], - [0.35189248608873791, 0.17034320478524959, 0.56650284911216653], - [0.35060304441931012, 0.16595129984720861, 0.56147964703993225], - [0.34924513554955644, 0.16161477763045118, 0.55634837474163779], - [0.34781653238777782, 0.15733863511152979, 0.55110853452703257], - [0.34631507175793091, 0.15312802296627787, 0.5457599924248665], - [0.34473901574536375, 0.14898820589826409, 0.54030245920406539], - [0.34308600291572294, 0.14492465359918028, 0.53473704282067103], - [0.34135411074506483, 0.1409427920655632, 0.52906500940336754], - [0.33954168752669694, 0.13704801896718169, 0.52328797535085236], - [0.33764732090671112, 0.13324562282438077, 0.51740807573979475], - [0.33566978565015315, 0.12954074251271822, 0.51142807215168951], - [0.33360804901486002, 0.12593818301005921, 0.50535164796654897], - [0.33146154891145124, 0.12244245263391232, 0.49918274588431072], - [0.32923005203231409, 0.11905764321981127, 0.49292595612342666], - [0.3269137124539796, 0.1157873496841953, 0.48658646495697461], - [0.32451307931207785, 0.11263459791730848, 0.48017007211645196], - [0.32202882276069322, 0.10960114111258401, 0.47368494725726878], - [0.31946262395497965, 0.10668879882392659, 0.46713728801395243], - [0.31681648089023501, 0.10389861387653518, 0.46053414662739794], - [0.31409278414755532, 0.10123077676403242, 0.45388335612058467], - [0.31129434479712365, 0.098684771934052201, 0.44719313715161618], - [0.30842444457210105, 0.096259385340577736, 0.44047194882050544], - [0.30548675819945936, 0.093952764840823738, 0.43372849999361113], - [0.30248536364574252, 0.091761187397303601, 0.42697404043749887], - [0.29942483960214772, 0.089682253716750038, 0.42021619665853854], - [0.29631000388905288, 0.087713250960463951, 0.41346259134143476], - [0.29314593096985248, 0.085850656889620708, 0.40672178082365834], - [0.28993792445176608, 0.08409078829085731, 0.40000214725256295], - [0.28669151388283165, 0.082429873848480689, 0.39331182532243375], - [0.28341239797185225, 0.080864153365499375, 0.38665868550105914], - [0.28010638576975472, 0.079389994802261526, 0.38005028528138707], - [0.27677939615815589, 0.078003941033788216, 0.37349382846504675], - [0.27343739342450812, 0.076702800237496066, 0.36699616136347685], - [0.27008637749114051, 0.075483675584275545, 0.36056376228111864], - [0.26673233211995284, 0.074344018028546205, 0.35420276066240958], - [0.26338121807151404, 0.073281657939897077, 0.34791888996380105], - [0.26003895187439957, 0.072294781043362205, 0.3417175669546984], - [0.25671191651083902, 0.071380106242082242, 0.33560648984600089], - [0.25340685873736807, 0.070533582926851829, 0.3295945757321303], - [0.25012845306199383, 0.069758206429106989, 0.32368100685760637], - [0.24688226237958999, 0.069053639449204451, 0.31786993834254956], - [0.24367372557466271, 0.068419855150922693, 0.31216524050888372], - [0.24050813332295939, 0.067857103814855602, 0.30657054493678321], - [0.23739062429054825, 0.067365888050555517, 0.30108922184065873], - [0.23433055727563878, 0.066935599661639394, 0.29574009929867601], - [0.23132955273021344, 0.066576186939090592, 0.29051361067988485], - [0.2283917709422868, 0.06628997924139618, 0.28541074411068496], - [0.22552164337737857, 0.066078173119395595, 0.28043398847505197], - [0.22272706739121817, 0.065933790675651943, 0.27559714652053702], - [0.22001251100779617, 0.065857918918907604, 0.27090279994325861], - [0.21737845072382705, 0.065859661233562045, 0.26634209349669508], - [0.21482843531473683, 0.065940385613778491, 0.26191675992376573], - [0.21237411048541005, 0.066085024661758446, 0.25765165093569542], - [0.21001214221188125, 0.066308573918947178, 0.2535289048041211], - [0.2077442377448806, 0.06661453200418091, 0.24954644291943817], - [0.20558051999470117, 0.066990462397868739, 0.24572497420147632], - [0.20352007949514977, 0.067444179612424215, 0.24205576625191821], - [0.20156133764129841, 0.067983271026200248, 0.23852974228695395], - [0.19971571438603364, 0.068592710553704722, 0.23517094067076993], - [0.19794834061899208, 0.069314066071660657, 0.23194647381302336], - [0.1960826032659409, 0.070321227242423623, 0.22874673279569585], - [0.19410351363791453, 0.071608304856891569, 0.22558727307410353], - [0.19199449184606268, 0.073182830649273306, 0.22243385243433622], - [0.18975853639094634, 0.075019861862143766, 0.2193005075652994], - [0.18739228342697645, 0.077102096899588329, 0.21618875376309582], - [0.18488035509396164, 0.079425730279723883, 0.21307651648984993], - [0.18774482037046955, 0.077251588468039312, 0.21387448578597812], - [0.19049578401722037, 0.075311278416787641, 0.2146562337112265], - [0.1931548636579131, 0.073606819040117955, 0.21542362939081539], - [0.19571853588267552, 0.072157781039602742, 0.21617499187076789], - [0.19819343656336558, 0.070974625252738788, 0.21690975060032436], - [0.20058760685133747, 0.070064576149984209, 0.21762721310371608], - [0.20290365333558247, 0.069435248580458964, 0.21833167885096033], - [0.20531725273301316, 0.068919592266397572, 0.21911516689288835], - [0.20785704662965598, 0.068484398797025281, 0.22000133917653536], - [0.21052882914958676, 0.06812195249816172, 0.22098759107715404], - [0.2133313859647627, 0.067830148426026665, 0.22207043213024291], - [0.21625279838647882, 0.067616330270516389, 0.22324568672294431], - [0.21930503925136402, 0.067465786362940039, 0.22451023616807558], - [0.22247308588973624, 0.067388214053092838, 0.22585960379408354], - [0.2257539681670791, 0.067382132300147474, 0.22728984778098055], - [0.22915620278592841, 0.067434730871152565, 0.22879681433956656], - [0.23266299920501882, 0.067557104388479783, 0.23037617493752832], - [0.23627495835774248, 0.06774359820987802, 0.23202360805926608], - [0.23999586188690308, 0.067985029964779953, 0.23373434258507808], - [0.24381149720247919, 0.068289851529011875, 0.23550427698321885], - [0.24772092990501099, 0.068653337909486523, 0.2373288009471749], - [0.25172899728289466, 0.069064630826035506, 0.23920260612763083], - [0.25582135547481771, 0.06953231029187984, 0.24112190491594204], - [0.25999463887892144, 0.070053855603861875, 0.24308218808684579], - [0.26425512207060942, 0.070616595622995437, 0.24507758869355967], - [0.26859095948172862, 0.071226716277922458, 0.24710443563450618], - [0.27299701518897301, 0.071883555446163511, 0.24915847093232929], - [0.27747150809142801, 0.072582969899254779, 0.25123493995942769], - [0.28201746297366942, 0.073315693214040967, 0.25332800295084507], - [0.28662309235899847, 0.074088460826808866, 0.25543478673717029], - [0.29128515387578635, 0.074899049847466703, 0.25755101595750435], - [0.2960004726065818, 0.075745336000958424, 0.25967245030364566], - [0.30077276812918691, 0.076617824336164764, 0.26179294097819672], - [0.30559226007249934, 0.077521963107537312, 0.26391006692119662], - [0.31045520848595526, 0.078456871676182177, 0.2660200572779356], - [0.31535870009205808, 0.079420997315243186, 0.26811904076941961], - [0.32029986557994061, 0.080412994737554838, 0.27020322893039511], - [0.32527888860401261, 0.081428390076546092, 0.27226772884656186], - [0.33029174471181438, 0.08246763389003825, 0.27430929404579435], - [0.33533353224455448, 0.083532434119003962, 0.27632534356790039], - [0.34040164359597463, 0.084622236191702671, 0.27831254595259397], - [0.34549355713871799, 0.085736654965126335, 0.28026769921081435], - [0.35060678246032478, 0.08687555176033529, 0.28218770540182386], - [0.35573889947341125, 0.088038974350243354, 0.2840695897279818], - [0.36088752387578377, 0.089227194362745205, 0.28591050458531014], - [0.36605031412464006, 0.090440685427697898, 0.2877077458811747], - [0.37122508431309342, 0.091679997480262732, 0.28945865397633169], - [0.3764103053221462, 0.092945198093777909, 0.29116024157313919], - [0.38160247377467543, 0.094238731263712183, 0.29281107506269488], - [0.38679939079544168, 0.09556181960083443, 0.29440901248173756], - [0.39199887556812907, 0.09691583650296684, 0.29595212005509081], - [0.39719876876325577, 0.098302320968278623, 0.29743856476285779], - [0.40239692379737496, 0.099722930314950553, 0.29886674369733968], - [0.40759120392688708, 0.10117945586419633, 0.30023519507728602], - [0.41277985630360303, 0.1026734006932461, 0.30154226437468967], - [0.41796105205173684, 0.10420644885760968, 0.30278652039631843], - [0.42313214269556043, 0.10578120994917611, 0.3039675809469457], - [0.42829101315789753, 0.1073997763055258, 0.30508479060294547], - [0.4334355841041439, 0.1090642347484701, 0.30613767928289148], - [0.43856378187931538, 0.11077667828375456, 0.30712600062348083], - [0.44367358645071275, 0.11253912421257944, 0.30804973095465449], - [0.44876299173174822, 0.11435355574622549, 0.30890905921943196], - [0.45383005086999889, 0.11622183788331528, 0.30970441249844921], - [0.45887288947308297, 0.11814571137706886, 0.31043636979038808], - [0.46389102840284874, 0.12012561256850712, 0.31110343446582983], - [0.46888111384598413, 0.12216445576414045, 0.31170911458932665], - [0.473841437035254, 0.12426354237989065, 0.31225470169927194], - [0.47877034239726296, 0.12642401401409453, 0.31274172735821959], - [0.48366628618847957, 0.12864679022013889, 0.31317188565991266], - [0.48852847371852987, 0.13093210934893723, 0.31354553695453014], - [0.49335504375145617, 0.13328091630401023, 0.31386561956734976], - [0.49814435462074153, 0.13569380302451714, 0.314135190862664], - [0.50289524974970612, 0.13817086581280427, 0.31435662153833671], - [0.50760681181053691, 0.14071192654913128, 0.31453200120082569], - [0.51227835105321762, 0.14331656120063752, 0.3146630922831542], - [0.51690848800544464, 0.14598463068714407, 0.31475407592280041], - [0.52149652863229956, 0.14871544765633712, 0.31480767954534428], - [0.52604189625477482, 0.15150818660835483, 0.31482653406646727], - [0.53054420489856446, 0.15436183633886777, 0.31481299789187128], - [0.5350027976174474, 0.15727540775107324, 0.31477085207396532], - [0.53941736649199057, 0.16024769309971934, 0.31470295028655965], - [0.54378771313608565, 0.16327738551419116, 0.31461204226295625], - [0.54811370033467621, 0.1663630904279047, 0.31450102990914708], - [0.55239521572711914, 0.16950338809328983, 0.31437291554615371], - [0.55663229034969341, 0.17269677158182117, 0.31423043195101424], - [0.56082499039117173, 0.17594170887918095, 0.31407639883970623], - [0.56497343529017696, 0.17923664950367169, 0.3139136046337036], - [0.56907784784011428, 0.18258004462335425, 0.31374440956796529], - [0.57313845754107873, 0.18597036007065024, 0.31357126868520002], - [0.57715550812992045, 0.18940601489760422, 0.31339704333572083], - [0.58112932761586555, 0.19288548904692518, 0.31322399394183942], - [0.58506024396466882, 0.19640737049066315, 0.31305401163732732], - [0.58894861935544707, 0.19997020971775276, 0.31288922211590126], - [0.59279480536520257, 0.20357251410079796, 0.31273234839304942], - [0.59659918109122367, 0.207212956082026, 0.31258523031121233], - [0.60036213010411577, 0.21089030138947745, 0.31244934410414688], - [0.60408401696732739, 0.21460331490206347, 0.31232652641170694], - [0.60776523994818654, 0.21835070166659282, 0.31221903291870201], - [0.6114062072731884, 0.22213124697023234, 0.31212881396435238], - [0.61500723236391375, 0.22594402043981826, 0.31205680685765741], - [0.61856865258877192, 0.22978799249179921, 0.31200463838728931], - [0.62209079821082613, 0.2336621873300741, 0.31197383273627388], - [0.62557416500434959, 0.23756535071152696, 0.31196698314912269], - [0.62901892016985872, 0.24149689191922535, 0.31198447195645718], - [0.63242534854210275, 0.24545598775548677, 0.31202765974624452], - [0.6357937104834237, 0.24944185818822678, 0.31209793953300591], - [0.6391243387840212, 0.25345365461983138, 0.31219689612063978], - [0.642417577481186, 0.257490519876798, 0.31232631707560987], - [0.64567349382645434, 0.26155203161615281, 0.31248673753935263], - [0.64889230169458245, 0.26563755336209077, 0.31267941819570189], - [0.65207417290277303, 0.26974650525236699, 0.31290560605819168], - [0.65521932609327127, 0.27387826652410152, 0.3131666792687211], - [0.6583280801134499, 0.27803210957665631, 0.3134643447952643], - [0.66140037532601781, 0.28220778870555907, 0.31379912926498488], - [0.66443632469878844, 0.28640483614256179, 0.31417223403606975], - [0.66743603766369131, 0.29062280081258873, 0.31458483752056837], - [0.67039959547676198, 0.29486126309253047, 0.31503813956872212], - [0.67332725564817331, 0.29911962764489264, 0.31553372323982209], - [0.67621897924409746, 0.30339762792450425, 0.3160724937230589], - [0.67907474028157344, 0.30769497879760166, 0.31665545668946665], - [0.68189457150944521, 0.31201133280550686, 0.31728380489244951], - [0.68467850942494535, 0.31634634821222207, 0.31795870784057567], - [0.68742656435169625, 0.32069970535138104, 0.31868137622277692], - [0.6901389321505248, 0.32507091815606004, 0.31945332332898302], - [0.69281544846764931, 0.32945984647042675, 0.3202754315314667], - [0.69545608346891119, 0.33386622163232865, 0.32114884306985791], - [0.6980608153581771, 0.33828976326048621, 0.32207478855218091], - [0.70062962477242097, 0.34273019305341756, 0.32305449047765694], - [0.70316249458814151, 0.34718723719597999, 0.32408913679491225], - [0.70565951122610093, 0.35166052978120937, 0.32518014084085567], - [0.70812059568420482, 0.35614985523380299, 0.32632861885644465], - [0.7105456546582587, 0.36065500290840113, 0.32753574162788762], - [0.71293466839773467, 0.36517570519856757, 0.3288027427038317], - [0.71528760614847287, 0.36971170225223449, 0.3301308728723546], - [0.71760444908133847, 0.37426272710686193, 0.33152138620958932], - [0.71988521490549851, 0.37882848839337313, 0.33297555200245399], - [0.7221299918421461, 0.38340864508963057, 0.33449469983585844], - [0.72433865647781592, 0.38800301593162145, 0.33607995965691828], - [0.72651122900227549, 0.3926113126792577, 0.3377325942005665], - [0.72864773856716547, 0.39723324476747235, 0.33945384341064017], - [0.73074820754845171, 0.401868526884681, 0.3412449533046818], - [0.73281270506268747, 0.4065168468778026, 0.34310715173410822], - [0.73484133598564938, 0.41117787004519513, 0.34504169470809071], - [0.73683422173585866, 0.41585125850290111, 0.34704978520758401], - [0.73879140024599266, 0.42053672992315327, 0.34913260148542435], - [0.74071301619506091, 0.4252339389526239, 0.35129130890802607], - [0.7425992159973317, 0.42994254036133867, 0.35352709245374592], - [0.74445018676570673, 0.43466217184617112, 0.35584108091122535], - [0.74626615789163442, 0.43939245044973502, 0.35823439142300639], - [0.74804739275559562, 0.44413297780351974, 0.36070813602540136], - [0.74979420547170472, 0.44888333481548809, 0.36326337558360278], - [0.75150685045891663, 0.45364314496866825, 0.36590112443835765], - [0.75318566369046569, 0.45841199172949604, 0.36862236642234769], - [0.75483105066959544, 0.46318942799460555, 0.3714280448394211], - [0.75644341577140706, 0.46797501437948458, 0.37431909037543515], - [0.75802325538455839, 0.4727682731566229, 0.37729635531096678], - [0.75957111105340058, 0.47756871222057079, 0.380360657784311], - [0.7610876378057071, 0.48237579130289127, 0.38351275723852291], - [0.76257333554052609, 0.48718906673415824, 0.38675335037837993], - [0.76402885609288662, 0.49200802533379656, 0.39008308392311997], - [0.76545492593330511, 0.49683212909727231, 0.39350254000115381], - [0.76685228950643891, 0.5016608471009063, 0.39701221751773474], - [0.76822176599735303, 0.50649362371287909, 0.40061257089416885], - [0.7695642334401418, 0.5113298901696085, 0.40430398069682483], - [0.77088091962302474, 0.51616892643469103, 0.40808667584648967], - [0.77217257229605551, 0.5210102658711383, 0.41196089987122869], - [0.77344021829889886, 0.52585332093451564, 0.41592679539764366], - [0.77468494746063199, 0.53069749384776732, 0.41998440356963762], - [0.77590790730685699, 0.53554217882461186, 0.42413367909988375], - [0.7771103295521099, 0.54038674910561235, 0.42837450371258479], - [0.77829345807633121, 0.54523059488426595, 0.432706647838971], - [0.77945862731506643, 0.55007308413977274, 0.43712979856444761], - [0.78060774749483774, 0.55491335744890613, 0.44164332426364639], - [0.78174180478981836, 0.55975098052594863, 0.44624687186865436], - [0.78286225264440912, 0.56458533111166875, 0.45093985823706345], - [0.78397060836414478, 0.56941578326710418, 0.45572154742892063], - [0.78506845019606841, 0.5742417003617839, 0.46059116206904965], - [0.78615737132332963, 0.5790624629815756, 0.46554778281918402], - [0.78723904108188347, 0.58387743744557208, 0.47059039582133383], - [0.78831514045623963, 0.58868600173562435, 0.47571791879076081], - [0.78938737766251943, 0.5934875421745599, 0.48092913815357724], - [0.79045776847727878, 0.59828134277062461, 0.48622257801969754], - [0.79152832843475607, 0.60306670593147205, 0.49159667021646397], - [0.79260034304237448, 0.60784322087037024, 0.49705020621532009], - [0.79367559698664958, 0.61261029334072192, 0.50258161291269432], - [0.79475585972654039, 0.61736734400220705, 0.50818921213102985], - [0.79584292379583765, 0.62211378808451145, 0.51387124091909786], - [0.79693854719951607, 0.62684905679296699, 0.5196258425240281], - [0.79804447815136637, 0.63157258225089552, 0.52545108144834785], - [0.7991624518501963, 0.63628379372029187, 0.53134495942561433], - [0.80029415389753977, 0.64098213306749863, 0.53730535185141037], - [0.80144124292560048, 0.64566703459218766, 0.5433300863249918], - [0.80260531146112946, 0.65033793748103852, 0.54941691584603647], - [0.80378792531077625, 0.65499426549472628, 0.55556350867083815], - [0.80499054790810298, 0.65963545027564163, 0.56176745110546977], - [0.80621460526927058, 0.66426089585282289, 0.56802629178649788], - [0.8074614045096935, 0.6688700095398864, 0.57433746373459582], - [0.80873219170089694, 0.67346216702194517, 0.58069834805576737], - [0.81002809466520687, 0.67803672673971815, 0.58710626908082753], - [0.81135014011763329, 0.68259301546243389, 0.59355848909050757], - [0.81269922039881493, 0.68713033714618876, 0.60005214820435104], - [0.81407611046993344, 0.69164794791482131, 0.6065843782630862], - [0.81548146627279483, 0.69614505508308089, 0.61315221209322646], - [0.81691575775055891, 0.70062083014783982, 0.61975260637257923], - [0.81837931164498223, 0.70507438189635097, 0.62638245478933297], - [0.81987230650455289, 0.70950474978787481, 0.63303857040067113], - [0.8213947205565636, 0.7139109141951604, 0.63971766697672761], - [0.82294635110428427, 0.71829177331290062, 0.6464164243818421], - [0.8245268129450285, 0.72264614312088882, 0.65313137915422603], - [0.82613549710580259, 0.72697275518238258, 0.65985900156216504], - [0.8277716072353446, 0.73127023324078089, 0.66659570204682972], - [0.82943407816481474, 0.7355371221572935, 0.67333772009301907], - [0.83112163529096306, 0.73977184647638616, 0.68008125203631464], - [0.83283277185777982, 0.74397271817459876, 0.68682235874648545], - [0.8345656905566583, 0.7481379479992134, 0.69355697649863846], - [0.83631898844737929, 0.75226548952875261, 0.70027999028864962], - [0.83809123476131964, 0.75635314860808633, 0.70698561390212977], - [0.83987839884120874, 0.76039907199779677, 0.71367147811129228], - [0.84167750766845151, 0.76440101200982946, 0.72033299387284622], - [0.84348529222933699, 0.76835660399870176, 0.72696536998972039], - [0.84529810731955113, 0.77226338601044719, 0.73356368240541492], - [0.84711195507965098, 0.77611880236047159, 0.74012275762807056], - [0.84892245563117641, 0.77992021407650147, 0.74663719293664366], - [0.85072697023178789, 0.78366457342383888, 0.7530974636118285], - [0.85251907207708444, 0.78734936133548439, 0.7594994148789691], - [0.85429219611470464, 0.79097196777091994, 0.76583801477914104], - [0.85604022314725403, 0.79452963601550608, 0.77210610037674143], - [0.85775662943504905, 0.79801963142713928, 0.77829571667247499], - [0.8594346370300241, 0.8014392309950078, 0.78439788751383921], - [0.86107117027565516, 0.80478517909812231, 0.79039529663736285], - [0.86265601051127572, 0.80805523804261525, 0.796282666437655], - [0.86418343723941027, 0.81124644224653542, 0.80204612696863953], - [0.86564934325605325, 0.81435544067514909, 0.80766972324164554], - [0.86705314907048503, 0.81737804041911244, 0.81313419626911398], - [0.86839954695818633, 0.82030875512181523, 0.81841638963128993], - [0.86969131502613806, 0.82314158859569164, 0.82350476683173168], - [0.87093846717297507, 0.82586857889438514, 0.82838497261149613], - [0.87215331978454325, 0.82848052823709672, 0.8330486712880828], - [0.87335171360916275, 0.83096715251272624, 0.83748851001197089], - [0.87453793320260187, 0.83331972948645461, 0.84171925358069011], - [0.87571458709961403, 0.8355302318472394, 0.84575537519027078], - [0.87687848451614692, 0.83759238071186537, 0.84961373549150254], - [0.87802298436649007, 0.83950165618540074, 0.85330645352458923], - [0.87913244240792765, 0.84125554884475906, 0.85685572291039636], - [0.88019293315695812, 0.84285224824778615, 0.86027399927156634], - [0.88119169871341951, 0.84429066717717349, 0.86356595168669881], - [0.88211542489401606, 0.84557007254559347, 0.86673765046233331], - [0.88295168595448525, 0.84668970275699273, 0.86979617048190971], - [0.88369127145898041, 0.84764891761519268, 0.87274147101441557], - [0.88432713054113543, 0.84844741572055415, 0.87556785228242973], - [0.88485138159908572, 0.84908426422893801, 0.87828235285372469], - [0.88525897972630474, 0.84955892810989209, 0.88088414794024839], - [0.88554714811952384, 0.84987174283631584, 0.88336206121170946], - [0.88571155122845646, 0.85002186115856315, 0.88572538990087124]] - -_twilight_shifted_data = (_twilight_data[len(_twilight_data)//2:] + - _twilight_data[:len(_twilight_data)//2]) -_twilight_shifted_data.reverse() -_turbo_data = [[0.18995, 0.07176, 0.23217], - [0.19483, 0.08339, 0.26149], - [0.19956, 0.09498, 0.29024], - [0.20415, 0.10652, 0.31844], - [0.20860, 0.11802, 0.34607], - [0.21291, 0.12947, 0.37314], - [0.21708, 0.14087, 0.39964], - [0.22111, 0.15223, 0.42558], - [0.22500, 0.16354, 0.45096], - [0.22875, 0.17481, 0.47578], - [0.23236, 0.18603, 0.50004], - [0.23582, 0.19720, 0.52373], - [0.23915, 0.20833, 0.54686], - [0.24234, 0.21941, 0.56942], - [0.24539, 0.23044, 0.59142], - [0.24830, 0.24143, 0.61286], - [0.25107, 0.25237, 0.63374], - [0.25369, 0.26327, 0.65406], - [0.25618, 0.27412, 0.67381], - [0.25853, 0.28492, 0.69300], - [0.26074, 0.29568, 0.71162], - [0.26280, 0.30639, 0.72968], - [0.26473, 0.31706, 0.74718], - [0.26652, 0.32768, 0.76412], - [0.26816, 0.33825, 0.78050], - [0.26967, 0.34878, 0.79631], - [0.27103, 0.35926, 0.81156], - [0.27226, 0.36970, 0.82624], - [0.27334, 0.38008, 0.84037], - [0.27429, 0.39043, 0.85393], - [0.27509, 0.40072, 0.86692], - [0.27576, 0.41097, 0.87936], - [0.27628, 0.42118, 0.89123], - [0.27667, 0.43134, 0.90254], - [0.27691, 0.44145, 0.91328], - [0.27701, 0.45152, 0.92347], - [0.27698, 0.46153, 0.93309], - [0.27680, 0.47151, 0.94214], - [0.27648, 0.48144, 0.95064], - [0.27603, 0.49132, 0.95857], - [0.27543, 0.50115, 0.96594], - [0.27469, 0.51094, 0.97275], - [0.27381, 0.52069, 0.97899], - [0.27273, 0.53040, 0.98461], - [0.27106, 0.54015, 0.98930], - [0.26878, 0.54995, 0.99303], - [0.26592, 0.55979, 0.99583], - [0.26252, 0.56967, 0.99773], - [0.25862, 0.57958, 0.99876], - [0.25425, 0.58950, 0.99896], - [0.24946, 0.59943, 0.99835], - [0.24427, 0.60937, 0.99697], - [0.23874, 0.61931, 0.99485], - [0.23288, 0.62923, 0.99202], - [0.22676, 0.63913, 0.98851], - [0.22039, 0.64901, 0.98436], - [0.21382, 0.65886, 0.97959], - [0.20708, 0.66866, 0.97423], - [0.20021, 0.67842, 0.96833], - [0.19326, 0.68812, 0.96190], - [0.18625, 0.69775, 0.95498], - [0.17923, 0.70732, 0.94761], - [0.17223, 0.71680, 0.93981], - [0.16529, 0.72620, 0.93161], - [0.15844, 0.73551, 0.92305], - [0.15173, 0.74472, 0.91416], - [0.14519, 0.75381, 0.90496], - [0.13886, 0.76279, 0.89550], - [0.13278, 0.77165, 0.88580], - [0.12698, 0.78037, 0.87590], - [0.12151, 0.78896, 0.86581], - [0.11639, 0.79740, 0.85559], - [0.11167, 0.80569, 0.84525], - [0.10738, 0.81381, 0.83484], - [0.10357, 0.82177, 0.82437], - [0.10026, 0.82955, 0.81389], - [0.09750, 0.83714, 0.80342], - [0.09532, 0.84455, 0.79299], - [0.09377, 0.85175, 0.78264], - [0.09287, 0.85875, 0.77240], - [0.09267, 0.86554, 0.76230], - [0.09320, 0.87211, 0.75237], - [0.09451, 0.87844, 0.74265], - [0.09662, 0.88454, 0.73316], - [0.09958, 0.89040, 0.72393], - [0.10342, 0.89600, 0.71500], - [0.10815, 0.90142, 0.70599], - [0.11374, 0.90673, 0.69651], - [0.12014, 0.91193, 0.68660], - [0.12733, 0.91701, 0.67627], - [0.13526, 0.92197, 0.66556], - [0.14391, 0.92680, 0.65448], - [0.15323, 0.93151, 0.64308], - [0.16319, 0.93609, 0.63137], - [0.17377, 0.94053, 0.61938], - [0.18491, 0.94484, 0.60713], - [0.19659, 0.94901, 0.59466], - [0.20877, 0.95304, 0.58199], - [0.22142, 0.95692, 0.56914], - [0.23449, 0.96065, 0.55614], - [0.24797, 0.96423, 0.54303], - [0.26180, 0.96765, 0.52981], - [0.27597, 0.97092, 0.51653], - [0.29042, 0.97403, 0.50321], - [0.30513, 0.97697, 0.48987], - [0.32006, 0.97974, 0.47654], - [0.33517, 0.98234, 0.46325], - [0.35043, 0.98477, 0.45002], - [0.36581, 0.98702, 0.43688], - [0.38127, 0.98909, 0.42386], - [0.39678, 0.99098, 0.41098], - [0.41229, 0.99268, 0.39826], - [0.42778, 0.99419, 0.38575], - [0.44321, 0.99551, 0.37345], - [0.45854, 0.99663, 0.36140], - [0.47375, 0.99755, 0.34963], - [0.48879, 0.99828, 0.33816], - [0.50362, 0.99879, 0.32701], - [0.51822, 0.99910, 0.31622], - [0.53255, 0.99919, 0.30581], - [0.54658, 0.99907, 0.29581], - [0.56026, 0.99873, 0.28623], - [0.57357, 0.99817, 0.27712], - [0.58646, 0.99739, 0.26849], - [0.59891, 0.99638, 0.26038], - [0.61088, 0.99514, 0.25280], - [0.62233, 0.99366, 0.24579], - [0.63323, 0.99195, 0.23937], - [0.64362, 0.98999, 0.23356], - [0.65394, 0.98775, 0.22835], - [0.66428, 0.98524, 0.22370], - [0.67462, 0.98246, 0.21960], - [0.68494, 0.97941, 0.21602], - [0.69525, 0.97610, 0.21294], - [0.70553, 0.97255, 0.21032], - [0.71577, 0.96875, 0.20815], - [0.72596, 0.96470, 0.20640], - [0.73610, 0.96043, 0.20504], - [0.74617, 0.95593, 0.20406], - [0.75617, 0.95121, 0.20343], - [0.76608, 0.94627, 0.20311], - [0.77591, 0.94113, 0.20310], - [0.78563, 0.93579, 0.20336], - [0.79524, 0.93025, 0.20386], - [0.80473, 0.92452, 0.20459], - [0.81410, 0.91861, 0.20552], - [0.82333, 0.91253, 0.20663], - [0.83241, 0.90627, 0.20788], - [0.84133, 0.89986, 0.20926], - [0.85010, 0.89328, 0.21074], - [0.85868, 0.88655, 0.21230], - [0.86709, 0.87968, 0.21391], - [0.87530, 0.87267, 0.21555], - [0.88331, 0.86553, 0.21719], - [0.89112, 0.85826, 0.21880], - [0.89870, 0.85087, 0.22038], - [0.90605, 0.84337, 0.22188], - [0.91317, 0.83576, 0.22328], - [0.92004, 0.82806, 0.22456], - [0.92666, 0.82025, 0.22570], - [0.93301, 0.81236, 0.22667], - [0.93909, 0.80439, 0.22744], - [0.94489, 0.79634, 0.22800], - [0.95039, 0.78823, 0.22831], - [0.95560, 0.78005, 0.22836], - [0.96049, 0.77181, 0.22811], - [0.96507, 0.76352, 0.22754], - [0.96931, 0.75519, 0.22663], - [0.97323, 0.74682, 0.22536], - [0.97679, 0.73842, 0.22369], - [0.98000, 0.73000, 0.22161], - [0.98289, 0.72140, 0.21918], - [0.98549, 0.71250, 0.21650], - [0.98781, 0.70330, 0.21358], - [0.98986, 0.69382, 0.21043], - [0.99163, 0.68408, 0.20706], - [0.99314, 0.67408, 0.20348], - [0.99438, 0.66386, 0.19971], - [0.99535, 0.65341, 0.19577], - [0.99607, 0.64277, 0.19165], - [0.99654, 0.63193, 0.18738], - [0.99675, 0.62093, 0.18297], - [0.99672, 0.60977, 0.17842], - [0.99644, 0.59846, 0.17376], - [0.99593, 0.58703, 0.16899], - [0.99517, 0.57549, 0.16412], - [0.99419, 0.56386, 0.15918], - [0.99297, 0.55214, 0.15417], - [0.99153, 0.54036, 0.14910], - [0.98987, 0.52854, 0.14398], - [0.98799, 0.51667, 0.13883], - [0.98590, 0.50479, 0.13367], - [0.98360, 0.49291, 0.12849], - [0.98108, 0.48104, 0.12332], - [0.97837, 0.46920, 0.11817], - [0.97545, 0.45740, 0.11305], - [0.97234, 0.44565, 0.10797], - [0.96904, 0.43399, 0.10294], - [0.96555, 0.42241, 0.09798], - [0.96187, 0.41093, 0.09310], - [0.95801, 0.39958, 0.08831], - [0.95398, 0.38836, 0.08362], - [0.94977, 0.37729, 0.07905], - [0.94538, 0.36638, 0.07461], - [0.94084, 0.35566, 0.07031], - [0.93612, 0.34513, 0.06616], - [0.93125, 0.33482, 0.06218], - [0.92623, 0.32473, 0.05837], - [0.92105, 0.31489, 0.05475], - [0.91572, 0.30530, 0.05134], - [0.91024, 0.29599, 0.04814], - [0.90463, 0.28696, 0.04516], - [0.89888, 0.27824, 0.04243], - [0.89298, 0.26981, 0.03993], - [0.88691, 0.26152, 0.03753], - [0.88066, 0.25334, 0.03521], - [0.87422, 0.24526, 0.03297], - [0.86760, 0.23730, 0.03082], - [0.86079, 0.22945, 0.02875], - [0.85380, 0.22170, 0.02677], - [0.84662, 0.21407, 0.02487], - [0.83926, 0.20654, 0.02305], - [0.83172, 0.19912, 0.02131], - [0.82399, 0.19182, 0.01966], - [0.81608, 0.18462, 0.01809], - [0.80799, 0.17753, 0.01660], - [0.79971, 0.17055, 0.01520], - [0.79125, 0.16368, 0.01387], - [0.78260, 0.15693, 0.01264], - [0.77377, 0.15028, 0.01148], - [0.76476, 0.14374, 0.01041], - [0.75556, 0.13731, 0.00942], - [0.74617, 0.13098, 0.00851], - [0.73661, 0.12477, 0.00769], - [0.72686, 0.11867, 0.00695], - [0.71692, 0.11268, 0.00629], - [0.70680, 0.10680, 0.00571], - [0.69650, 0.10102, 0.00522], - [0.68602, 0.09536, 0.00481], - [0.67535, 0.08980, 0.00449], - [0.66449, 0.08436, 0.00424], - [0.65345, 0.07902, 0.00408], - [0.64223, 0.07380, 0.00401], - [0.63082, 0.06868, 0.00401], - [0.61923, 0.06367, 0.00410], - [0.60746, 0.05878, 0.00427], - [0.59550, 0.05399, 0.00453], - [0.58336, 0.04931, 0.00486], - [0.57103, 0.04474, 0.00529], - [0.55852, 0.04028, 0.00579], - [0.54583, 0.03593, 0.00638], - [0.53295, 0.03169, 0.00705], - [0.51989, 0.02756, 0.00780], - [0.50664, 0.02354, 0.00863], - [0.49321, 0.01963, 0.00955], - [0.47960, 0.01583, 0.01055]] - - -cmaps = { - name: ListedColormap(data, name=name) for name, data in [ - ('magma', _magma_data), - ('inferno', _inferno_data), - ('plasma', _plasma_data), - ('viridis', _viridis_data), - ('cividis', _cividis_data), - ('twilight', _twilight_data), - ('twilight_shifted', _twilight_shifted_data), - ('turbo', _turbo_data), - ]} diff --git a/spaces/lambdalabs/LambdaSuperRes/KAIR/retinaface/data_faces/__init__.py b/spaces/lambdalabs/LambdaSuperRes/KAIR/retinaface/data_faces/__init__.py deleted file mode 100644 index ea50ebaf88d64e75f4960bc99b14f138a343e575..0000000000000000000000000000000000000000 --- a/spaces/lambdalabs/LambdaSuperRes/KAIR/retinaface/data_faces/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .wider_face import WiderFaceDetection, detection_collate -from .data_augment import * -from .config import * diff --git a/spaces/leogabraneth/text-generation-webui-main/extensions/ngrok/script.py b/spaces/leogabraneth/text-generation-webui-main/extensions/ngrok/script.py deleted file mode 100644 index 46f39bd327b6046f8e0d38ef266fc7d3687640da..0000000000000000000000000000000000000000 --- a/spaces/leogabraneth/text-generation-webui-main/extensions/ngrok/script.py +++ /dev/null @@ -1,36 +0,0 @@ -# Adds ngrok ingress, to use add `--extension ngrok` to the command line options -# -# Parameters can be customized in settings.json of webui, e.g.: -# {"ngrok": {"basic_auth":"user:password"} } -# or -# {"ngrok": {"oauth_provider":"google", "oauth_allow_emails":["asdf@asdf.com"]} } -# -# See this example for full list of options: https://github.com/ngrok/ngrok-py/blob/main/examples/ngrok-connect-full.py -# or the README.md in this directory. - -import logging -from modules import shared - -# Pick up host/port command line arguments -host = shared.args.listen_host if shared.args.listen_host and shared.args.listen else '127.0.0.1' -port = shared.args.listen_port if shared.args.listen_port else '7860' - -# Default options -options = { - 'addr': f"{host}:{port}", - 'authtoken_from_env': True, - 'session_metadata': 'text-generation-webui', -} - - -def ui(): - settings = shared.settings.get("ngrok") - if settings: - options.update(settings) - - try: - import ngrok - tunnel = ngrok.connect(**options) - logging.info(f"Ingress established at: {tunnel.url()}") - except ModuleNotFoundError: - logging.error("===> ngrok library not found, please run `pip install -r extensions/ngrok/requirements.txt`") diff --git a/spaces/leogabraneth/text-generation-webui-main/modules/ui_session.py b/spaces/leogabraneth/text-generation-webui-main/modules/ui_session.py deleted file mode 100644 index 13610fcd30105e0cefe89a63b34f40c2bffd8d9d..0000000000000000000000000000000000000000 --- a/spaces/leogabraneth/text-generation-webui-main/modules/ui_session.py +++ /dev/null @@ -1,68 +0,0 @@ -import gradio as gr - -from modules import shared, ui, utils -from modules.github import clone_or_pull_repository -from modules.utils import gradio - - -def create_ui(): - mu = shared.args.multi_user - with gr.Tab("Session", elem_id="session-tab"): - with gr.Row(): - with gr.Column(): - shared.gradio['reset_interface'] = gr.Button("Apply flags/extensions and restart", interactive=not mu) - with gr.Row(): - shared.gradio['toggle_dark_mode'] = gr.Button('Toggle 💡') - shared.gradio['save_settings'] = gr.Button('Save UI defaults to settings.yaml', interactive=not mu) - - with gr.Row(): - with gr.Column(): - shared.gradio['extensions_menu'] = gr.CheckboxGroup(choices=utils.get_available_extensions(), value=shared.args.extensions, label="Available extensions", info='Note that some of these extensions may require manually installing Python requirements through the command: pip install -r extensions/extension_name/requirements.txt', elem_classes='checkboxgroup-table') - - with gr.Column(): - shared.gradio['bool_menu'] = gr.CheckboxGroup(choices=get_boolean_arguments(), value=get_boolean_arguments(active=True), label="Boolean command-line flags", elem_classes='checkboxgroup-table') - - with gr.Column(): - extension_name = gr.Textbox(lines=1, label='Install or update an extension', info='Enter the GitHub URL below and press Enter. For a list of extensions, see: https://github.com/oobabooga/text-generation-webui-extensions ⚠️ WARNING ⚠️ : extensions can execute arbitrary code. Make sure to inspect their source code before activating them.', interactive=not mu) - extension_status = gr.Markdown() - - extension_name.submit(clone_or_pull_repository, extension_name, extension_status, show_progress=False) - - # Reset interface event - shared.gradio['reset_interface'].click( - set_interface_arguments, gradio('extensions_menu', 'bool_menu'), None).then( - lambda: None, None, None, _js='() => {document.body.innerHTML=\'

    Reloading...

    \'; setTimeout(function(){location.reload()},2500); return []}') - - shared.gradio['toggle_dark_mode'].click(lambda: None, None, None, _js='() => {document.getElementsByTagName("body")[0].classList.toggle("dark")}') - shared.gradio['save_settings'].click( - ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then( - ui.save_settings, gradio('interface_state', 'preset_menu', 'instruction_template', 'extensions_menu', 'show_controls'), gradio('save_contents')).then( - lambda: './', None, gradio('save_root')).then( - lambda: 'settings.yaml', None, gradio('save_filename')).then( - lambda: gr.update(visible=True), None, gradio('file_saver')) - - -def set_interface_arguments(extensions, bool_active): - shared.args.extensions = extensions - - bool_list = get_boolean_arguments() - - for k in bool_list: - setattr(shared.args, k, False) - for k in bool_active: - setattr(shared.args, k, True) - - shared.need_restart = True - - -def get_boolean_arguments(active=False): - exclude = ["default", "notebook", "chat"] - - cmd_list = vars(shared.args) - bool_list = sorted([k for k in cmd_list if type(cmd_list[k]) is bool and k not in exclude + ui.list_model_elements()]) - bool_active = [k for k in bool_list if vars(shared.args)[k]] - - if active: - return bool_active - else: - return bool_list diff --git a/spaces/leurez/moss/config/index.ts b/spaces/leurez/moss/config/index.ts deleted file mode 100644 index e739ac85628835db30e67aa401bfea63b1005f1a..0000000000000000000000000000000000000000 --- a/spaces/leurez/moss/config/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './proxy' diff --git a/spaces/limcheekin/orca_mini_v3_13B-GGML/main.py b/spaces/limcheekin/orca_mini_v3_13B-GGML/main.py deleted file mode 100644 index 1918eba50f57952f9a9c6aba68cfa3823322a710..0000000000000000000000000000000000000000 --- a/spaces/limcheekin/orca_mini_v3_13B-GGML/main.py +++ /dev/null @@ -1,27 +0,0 @@ -from llama_cpp.server.app import create_app, Settings -from fastapi.responses import HTMLResponse -import os - -app = create_app( - Settings( - n_threads=2, # set to number of cpu cores - model="model/ggmlv3-model.bin", - embedding=False - ) -) - -# Read the content of index.html once and store it in memory -with open("index.html", "r") as f: - content = f.read() - - -@app.get("/", response_class=HTMLResponse) -async def read_items(): - return content - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, - host=os.environ["HOST"], - port=int(os.environ["PORT"]) - ) diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Api 609 Pdf Free 23.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Api 609 Pdf Free 23.md deleted file mode 100644 index 174121b0f27f62448411614e53bb3ab38ed4c066..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Api 609 Pdf Free 23.md +++ /dev/null @@ -1,77 +0,0 @@ -
    -

    Api 609 Pdf Free 23: How to Download and Read the API Standard for Butterfly Valves

    - -

    If you are interested in learning more about butterfly valves, especially the double flanged, lug- and wafer-type, you may want to download and read the Api 609 Pdf Free 23. This is a PDF file that contains the eighth edition of the API Standard 609, which covers the design, materials, face-to-face dimensions, pressure-temperature ratings, and examination, inspection and test requirements for gray iron, ductile iron, bronze, steel, nickel-based alloy, or special alloy butterfly valves.

    -

    Api 609 Pdf Free 23


    Download Filehttps://bytlly.com/2uGxce



    - -

    Api 609 Pdf Free 23 is a useful resource for engineers, designers, manufacturers, and users of butterfly valves. It provides detailed information and guidance on how to select, install, operate, and maintain butterfly valves in various applications. It also includes typical valve construction and nomenclature for valve parts.

    - -

    In this article, we will show you how to download and read the Api 609 Pdf Free 23. We will also explain what are the benefits and features of the API Standard 609 for butterfly valves.

    - -

    How to Download the Api 609 Pdf Free 23?

    - -

    If you want to download the Api 609 Pdf Free 23, you need to follow these steps:

    - -
      -
    1. Find a reliable website that offers the Api 609 Pdf Free 23. Some of the websites that claim to offer free PDF files may be fake or malicious, so be careful and do some research before downloading anything. Some of the websites that we found that offer the Api 609 Pdf Free 23 are: - - -
    2. -
    3. Download the Api 609 Pdf Free 23 from the website of your choice. You may need to click on a download button or a link to start the download. The PDF file should be about 36 pages long and have a size of about 1 MB.
    4. -
    5. Open the Api 609 Pdf Free 23 with a PDF reader software application such as Adobe Acrobat Reader or Foxit Reader. You can download them for free from their official websites.
    6. -
    7. Enjoy reading the Api 609 Pdf Free 23!
    8. -
    - -

    What are the Benefits and Features of the API Standard 609 for Butterfly Valves?

    - -

    The API Standard 609 for butterfly valves has some benefits and features that you should be aware of before reading it. Here are some of them:

    - -
      -
    • The API Standard 609 covers two categories of butterfly valves: Category A and Category B. Category A are manufacturer’s rated cold working pressure (CWP) butterfly valves, usually with a concentric disc and seat configuration. Category B are ASME Class and pressure-temperature rated butterfly valves that have an offset seat and either an eccentric or a concentric disc configuration. These valves may have a seat rating less than the body rating.
    • -
    • The API Standard 609 covers different sizes and classes of butterfly valves. For lug and wafer, Class 150: NPS 3 to NPS 48. For lug and wafer, Class 300 and Class 600: NPS 3 to NPS 48. For double-flanged long pattern, Class 150, 300, and -600: NPS 3 to NPS 36. For double-flanged short pattern, Class 150 and Class -300: NPS 3 to NPS 48. For double-flanged short pattern, Class -600: NPS

      -

      -

      What are the Applications and Advantages of Butterfly Valves?

      - -

      Butterfly valves are widely used in various industries and applications, such as oil and gas, chemical, power, water, and HVAC. They are suitable for controlling the flow of liquids, gases, or solids in pipes or ducts. They can also be used for isolation, throttling, or regulation purposes.

      - -

      Butterfly valves have some advantages over other types of valves, such as ball valves or gate valves. Some of these advantages are:

      - -
        -
      • Butterfly valves are compact and lightweight, which makes them easy to install and maintain.
      • -
      • Butterfly valves have a simple and robust design, which reduces the risk of leakage and failure.
      • -
      • Butterfly valves have a low pressure drop and high flow capacity, which improves the efficiency and performance of the system.
      • -
      • Butterfly valves can handle a wide range of temperatures and pressures, as well as corrosive or abrasive media.
      • -
      • Butterfly valves can be operated manually or automatically, using a handle, a lever, a gear, an actuator, or a control system.
      • -
      - -

      What are the Types and Features of Butterfly Valves?

      - -

      There are different types and features of butterfly valves, depending on their design, configuration, material, and function. Some of the common types and features of butterfly valves are:

      - -
        -
      • Concentric butterfly valves: These are the simplest and most common type of butterfly valves. They have a disc that is centered on the valve stem and rotates around it. The disc has the same shape and size as the valve bore. The seat is usually made of rubber or plastic and is attached to the valve body.
      • -
      • Eccentric butterfly valves: These are more advanced and complex type of butterfly valves. They have a disc that is offset from the valve stem and rotates around it. The disc has a different shape or size than the valve bore. The seat is usually made of metal or composite material and is attached to the disc or the valve body.
      • -
      • Lug-type butterfly valves: These are a type of butterfly valves that have threaded inserts on both sides of the valve body. They can be installed between two flanges or on the end of a pipe. They can also be used for dead-end service.
      • -
      • Wafer-type butterfly valves: These are a type of butterfly valves that have no threaded inserts on the valve body. They can only be installed between two flanges using bolts that pass through the flanges and the valve body. They cannot be used for dead-end service.
      • -
      • Double-flanged butterfly valves: These are a type of butterfly valves that have flanges on both ends of the valve body. They can be installed between two flanges or on the end of a pipe. They can also be used for dead-end service.
      • -
      - -

      Conclusion

      - -

      In this article, we have shown you how to download and read the Api 609 Pdf Free 23. We have also explained what are the benefits and features of the API Standard 609 for butterfly valves.

      - -

      We hope this article has been helpful and informative for you. If you have any questions or comments, feel free to leave them below.

      -

      Conclusion

      - -

      In this article, we have shown you how to download and read the Api 609 Pdf Free 23. We have also explained what are the benefits and features of the API Standard 609 for butterfly valves.

      - -

      We hope this article has been helpful and informative for you. If you have any questions or comments, feel free to leave them below.

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Libro El Secreto De Las Edades Robert Collier Pdf.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Libro El Secreto De Las Edades Robert Collier Pdf.md deleted file mode 100644 index 1299491389f77518b49de70f16c2a70c45873d6e..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Libro El Secreto De Las Edades Robert Collier Pdf.md +++ /dev/null @@ -1,8 +0,0 @@ -

      Libro El Secreto De Las Edades Robert Collier Pdf


      Download File ✓✓✓ https://bytlly.com/2uGwdS



      -
      -Rank This Game - Right Now:. These are my other most played games. Watch this great Cuban athlete play rugby with some hilarious moves! The Online Machinima Movie Maker. The Great Gatsby: Revised Edition. How long have you been playing? Ive been playing since i was 2. How to Read Strikers' Knees. Why not watch a movie with the kids? Click on the first purple circle. The great thing about netflix is you can watch tv shows that youve never watched. The - 22 Mar 2014 Google Chrome Reading View. - -Tags: empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las Edades Robert Collier Pdf, empresa El Secreto De Las 4fefd39f24
      -
      -
      -

      diff --git a/spaces/lunadebruyne/EmotioNL/app_dataset.py b/spaces/lunadebruyne/EmotioNL/app_dataset.py deleted file mode 100644 index 83813c39b02bf77963f0f066eb8b39716987cf12..0000000000000000000000000000000000000000 --- a/spaces/lunadebruyne/EmotioNL/app_dataset.py +++ /dev/null @@ -1,381 +0,0 @@ -import gradio as gr -import torch -import numpy as np -import pickle - -import pandas as pd -from tqdm import tqdm - -import altair as alt -import matplotlib.pyplot as plt -from datetime import date, timedelta - -from transformers import AutoTokenizer, AutoConfig, AutoModel, AutoModelForSequenceClassification - -""" -description_sentence = "

      Demo EmotioNL

      \nThis demo allows you to analyse the emotion in a sentence." -description_dataset = "

      Demo EmotioNL

      \nThis demo allows you to analyse the emotions in a dataset.\nThe data should be in tsv-format with two named columns: the first column (id) should contain the sentence IDs, and the second column (text) should contain the actual texts. Optionally, there is a third column named 'date', which specifies the date associated with the text (e.g., tweet date). This column is necessary when the options 'emotion distribution over time' and 'peaks' are selected." -inference_modelpath = "model/checkpoint-128" -def inference_sentence(text): - tokenizer = AutoTokenizer.from_pretrained(inference_modelpath) - model = AutoModelForSequenceClassification.from_pretrained(inference_modelpath) - for text in tqdm([text]): - inputs = tokenizer(text, return_tensors="pt") - with torch.no_grad(): # run model - logits = model(**inputs).logits - predicted_class_id = logits.argmax().item() - output = model.config.id2label[predicted_class_id] - return output -def frequencies(preds): - preds_dict = {"neutral": 0, "anger": 0, "fear": 0, "joy": 0, "love": 0, "sadness": 0} - for pred in preds: - preds_dict[pred] = preds_dict[pred] + 1 - bars = list(preds_dict.keys()) - height = list(preds_dict.values()) - x_pos = np.arange(len(bars)) - plt.bar(x_pos, height, color=['lightgrey', 'firebrick', 'rebeccapurple', 'orange', 'palevioletred', 'cornflowerblue']) - plt.xticks(x_pos, bars) - return plt - -def inference_dataset(file_object, option_list): - tokenizer = AutoTokenizer.from_pretrained(inference_modelpath) - model = AutoModelForSequenceClassification.from_pretrained(inference_modelpath) - data_path = open(file_object.name, 'r') - df = pd.read_csv(data_path, delimiter='\t', header=0, names=['id', 'text']) - ids = df["id"].tolist() - texts = df["text"].tolist() - preds = [] - for text in tqdm(texts): # progressbar - inputs = tokenizer(text, return_tensors="pt") - with torch.no_grad(): # run model - logits = model(**inputs).logits - predicted_class_id = logits.argmax().item() - prediction = model.config.id2label[predicted_class_id] - preds.append(prediction) - predictions_content = list(zip(ids, texts, preds)) - # write predictions to file - output = "output.txt" - f = open(output, 'w') - f.write("id\ttext\tprediction\n") - for line in predictions_content: - f.write(str(line[0]) + '\t' + str(line[1]) + '\t' + str(line[2]) + '\n') - output1 = output - output2 = output3 = output4 = output5 = "This option was not selected." - if "emotion frequencies" in option_list: - output2 = frequencies(preds) - else: - output2 = None - if "emotion distribution over time" in option_list: - output3 = "This option was selected." - if "peaks" in option_list: - output4 = "This option was selected." - if "topics" in option_list: - output5 = "This option was selected." - return [output1, output2, output3, output4, output5] -iface_sentence = gr.Interface( - fn=inference_sentence, - description = description_sentence, - inputs = gr.Textbox( - label="Enter a sentence", - lines=1), - outputs="text") -inputs = [gr.File( - label="Upload a dataset"), - gr.CheckboxGroup( - ["emotion frequencies", "emotion distribution over time", "peaks", "topics"], - label = "Select options")] -outputs = [gr.File(), - gr.Plot(label="Emotion frequencies"), - gr.Textbox(label="Emotion distribution over time"), - gr.Textbox(label="Peaks"), - gr.Textbox(label="Topics")] -iface_dataset = gr.Interface( - fn = inference_dataset, - description = description_dataset, - inputs=inputs, - outputs = outputs) -iface = gr.TabbedInterface([iface_sentence, iface_dataset], ["Sentence", "Dataset"]) -iface.queue().launch() -""" - -inference_modelpath = "model/checkpoint-128" - -def inference_sentence(text): - tokenizer = AutoTokenizer.from_pretrained(inference_modelpath) - model = AutoModelForSequenceClassification.from_pretrained(inference_modelpath) - for text in tqdm([text]): - inputs = tokenizer(text, return_tensors="pt") - with torch.no_grad(): # run model - logits = model(**inputs).logits - predicted_class_id = logits.argmax().item() - output = model.config.id2label[predicted_class_id] - return "Predicted emotion:\n" + output -""" -def inference_sentence(text): - output = "This sentence will be processed:\n" + text - return output -""" - -def unavailable(input_file, input_checks): - output = "As we are currently updating this demo, submitting your own data is unavailable for the moment. However, you can try out the showcase mode 😊" - return gr.update(visible=True), gr.update(value=output, label="Oops!", visible=True) - -def showcase(input_file): - output = "showcase/example_predictions.txt" - return gr.update(visible=True), gr.update(visible=False), gr.update(value=output, visible=True), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) # next_button_freq becomes available - -def file(input_file, input_checks): - #output = "output.txt" - #f = open(output, 'w') - #f.write("The predictions come here.") - #f.close() - output = "showcase/example_predictions.txt" - if "emotion frequencies" in input_checks: - return gr.update(value=output, visible=True), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) # next_button_freq becomes available - elif "emotion distribution over time" in input_checks: - return gr.update(value=output, visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) # next_button_dist becomes available - elif "peaks" in input_checks: - return gr.update(value=output, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) # next_button_peaks becomes available - elif "topics" in input_checks: - return gr.update(value=output, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) # next_button_topics becomes available - else: - return gr.update(value=output, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) # no next_button becomes available - -def freq(output_file, input_checks): - #simple = pd.DataFrame({ - #'Emotion category': ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness'], - #'Frequency': [10, 8, 2, 15, 3, 4]}) - - f = open("showcase/example_predictions.txt", 'r') - data = f.read().split("\n") - f.close() - data = [line.split("\t") for line in data[1:-1]] - - freq_dict = {} - for line in data: - if line[1] not in freq_dict.keys(): - freq_dict[line[1]] = 1 - else: - freq_dict[line[1]] += 1 - - simple = pd.DataFrame({ - 'Emotion category': ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness'], - 'Frequency': [freq_dict['neutral'], freq_dict['anger'], freq_dict['fear'], freq_dict['joy'], freq_dict['love'], freq_dict['sadness']]}) - - domain = ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness'] - range_ = ['#999999', '#b22222', '#663399', '#ffcc00', '#db7093', '#6495ed'] - n = max(simple['Frequency']) - - plot = alt.Chart(simple).mark_bar().encode( - x=alt.X("Emotion category", sort=['neutral', 'anger', 'fear', 'joy', 'love', 'sadness']), - y=alt.Y("Frequency", axis=alt.Axis(grid=False), scale=alt.Scale(domain=[0, (n + 9) // 10 * 10])), - color=alt.Color("Emotion category", scale=alt.Scale(domain=domain, range=range_), legend=None), - tooltip=['Emotion category', 'Frequency']).properties( - width=600).configure_axis( - grid=False).interactive() - - if "emotion distribution over time" in input_checks or (output_file.name).startswith('/tmp/example_predictions'): - return gr.update(value=plot, visible=True), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) # next_button_dist becomes available - elif "peaks" in input_checks: - return gr.update(value=plot, visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) # next_button_peaks becomes available - elif "topics" in input_checks: - return gr.update(value=plot, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) # next_button_topics becomes available - else: - return gr.update(value=plot, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) # no next_button becomes available - - -def dist(output_file, input_checks): - #data = pd.DataFrame({ - #'Date': ['1/1', '1/1', '1/1', '1/1', '1/1', '1/1', '2/1', '2/1', '2/1', '2/1', '2/1', '2/1', '3/1', '3/1', '3/1', '3/1', '3/1', '3/1'], - #'Frequency': [3, 5, 1, 8, 2, 3, 4, 7, 1, 12, 4, 2, 3, 6, 3, 10, 3, 4], - #'Emotion category': ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness', 'neutral', 'anger', 'fear', 'joy', 'love', 'sadness', 'neutral', 'anger', 'fear', 'joy', 'love', 'sadness']}) - - f = open("showcase/data.txt", 'r') - data = f.read().split("\n") - f.close() - data = [line.split("\t") for line in data[1:-1]] - - freq_dict = {} - for line in data: - dat = str(date(2000+int(line[0].split("/")[2]), int(line[0].split("/")[1]), int(line[0].split("/")[0]))) - if dat not in freq_dict.keys(): - freq_dict[dat] = {} - if line[1] not in freq_dict[dat].keys(): - freq_dict[dat][line[1]] = 1 - else: - freq_dict[dat][line[1]] += 1 - else: - if line[1] not in freq_dict[dat].keys(): - freq_dict[dat][line[1]] = 1 - else: - freq_dict[dat][line[1]] += 1 - - start_date = date(2000+int(data[0][0].split("/")[2]), int(data[0][0].split("/")[1]), int(data[0][0].split("/")[0])) - end_date = date(2000+int(data[-1][0].split("/")[2]), int(data[-1][0].split("/")[1]), int(data[-1][0].split("/")[0])) - delta = end_date - start_date # returns timedelta - date_range = [str(start_date + timedelta(days=i)) for i in range(delta.days + 1)] - - dates = [dat for dat in date_range for i in range(6)] - frequency = [freq_dict[dat][emotion] if (dat in freq_dict.keys() and emotion in freq_dict[dat].keys()) else 0 for dat in date_range for emotion in ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness']] - categories = [emotion for dat in date_range for emotion in ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness']] - - data = pd.DataFrame({ - 'Date': dates, - 'Frequency': frequency, - 'Emotion category': categories}) - - domain = ['neutral', 'anger', 'fear', 'joy', 'love', 'sadness'] - range_ = ['#999999', '#b22222', '#663399', '#ffcc00', '#db7093', '#6495ed'] - n = max(data['Frequency']) - - highlight = alt.selection( - type='single', on='mouseover', fields=["Emotion category"], nearest=True) - - - base = alt.Chart(data).encode( - x ="Date:T", - y=alt.Y("Frequency", scale=alt.Scale(domain=[0, (n + 9) // 10 * 10])), - color=alt.Color("Emotion category", scale=alt.Scale(domain=domain, range=range_), legend=alt.Legend(orient='bottom', direction='horizontal'))) - - - points = base.mark_circle().encode( - opacity=alt.value(0), - tooltip=[ - alt.Tooltip('Emotion category', title='Emotion category'), - alt.Tooltip('Date:T', title='Date'), - alt.Tooltip('Frequency', title='Frequency') - ]).add_selection(highlight) - - - lines = base.mark_line().encode( - size=alt.condition(~highlight, alt.value(1), alt.value(3))) - - plot = (points + lines).properties(width=600, height=350).interactive() - - if "peaks" in input_checks or (output_file.name).startswith('/tmp/example_predictions'): - return gr.Plot.update(value=plot, visible=True), gr.update(visible=True), gr.update(visible=False) # next_button_peaks becomes available - elif "topics" in input_checks: - return gr.Plot.update(value=plot, visible=True), gr.update(visible=False), gr.update(visible=True) # next_button_topics becomes available - else: - return gr.Plot.update(value=plot, visible=True), gr.update(visible=False), gr.update(visible=False) # no next_button becomes available - -def peaks(output_file, input_checks): - plot = pickle.load(open('showcase/peaks_covid.p', 'rb')) - if "topics" in input_checks or (output_file.name).startswith('/tmp/example_predictions'): - return gr.Plot.update(value=plot, visible=True), gr.update(visible=True) # next_button_topics becomes available - else: - return gr.Plot.update(value=plot, visible=True), gr.update(visible=False) # no next_button becomes available - -def topics(output_file, input_checks): - plot = pickle.load(open('showcase/vis_classes_covid.p', 'rb')) - plot.update_layout(width=600, height=400) - return gr.Plot.update(value=plot, visible=True) # no next_button becomes available - -# This demo was made to demonstrate the EmotioNL model, a transformer-based classification model that analyses emotions in Dutch texts. The model uses [RobBERT](https://github.com/iPieter/RobBERT), which was further fine-tuned on the [EmotioNL dataset](https://lt3.ugent.be/resources/emotionl/). The resulting model is a classifier that, given a sentence, predicts one of the following emotion categories: _anger_, _fear_, _joy_, _love_, _sadness_ or _neutral_. The demo can be used either in **sentence mode**, which allows you to enter a sentence for which an emotion will be predicted; or in **dataset mode**, which allows you to upload a dataset or see the full functuonality of with example data. - - -with gr.Blocks() as demo: - with gr.Column(scale=1, min_width=50): - gr.Markdown(""" - """) - with gr.Column(scale=5): - gr.Markdown(""" -

      EmotioNL: A framework for Dutch emotion detection

      - -
      EmotioNL logo
      - -
      This demo was made to demonstrate the EmotioNL model, a transformer-based classification model that analyses emotions in Dutch texts. The model uses RobBERT, which was further fine-tuned on the EmotioNL dataset. The resulting model is a classifier that, given a sentence, predicts one of the following emotion categories: anger, fear, joy, love, sadness or neutral. The demo can be used either in sentence mode, which allows you to enter a sentence for which an emotion will be predicted; or in dataset mode, which allows you to upload a dataset or see the full functionality with example data.
      - """) - with gr.Tab("Sentence"): - gr.Markdown(""" - """) - with gr.Row(): - with gr.Column(): - input = gr.Textbox( - label="Enter a sentence", - value="Jaaah! Volgende vakantie Barcelona en na het zomerseizoen naar de Algarve", - lines=1) - send_btn = gr.Button("Send") - output = gr.Textbox() - send_btn.click(fn=inference_sentence, inputs=input, outputs=output) - with gr.Tab("Dataset"): - gr.Markdown(""" - _As we are currently updating this demo, submitting your own data is unavailable for the moment._ - _Try out the showcase mode._ - """) - with gr.Row(): - with gr.Column(): - demo_btn = gr.Button("Showcase with example data", variant="primary") - with gr.Column(): - gr.Markdown(""" - **Run in showcase mode or use your own data** - Try out the demo in showcase mode, which uses example data (609,206 tweets about the COVID-19 pandemic) with all the options provided by the demo, or upload your own dataset. - """) - with gr.Row(): - with gr.Column(): - input_file = gr.File( - label="Upload a dataset") - input_checks = gr.CheckboxGroup( - ["emotion frequencies", "emotion distribution over time", "peaks", "topics"], - label = "Select options") - send_btn = gr.Button("Submit data") - with gr.Column(): - gr.Markdown(""" - **Data format** - The data should be in tsv-format with two named columns: the first column (id) should contain the sentence IDs, and the second column (text) should contain the actual texts. Optionally, there is a third column named 'date', which specifies the date associated with the text (e.g., tweet date). This column is necessary when the options 'emotion distribution over time' and 'peaks' are selected. For now, we only accept files with maximum 400 sentences and a limit of 300 tokens per sentence. - - **Options** - **Emotion frequencies** outputs a bar plot with the prediction frequencies of each emotion category (anger, fear, joy, love, sadness or neutral). - **Emotion distribution over time** outputs a line plot that visualises the frequency of predicted emotions over time for each emotion category. - **Peaks** outputs a step graph that only shows the significant fluctuations (upwards and downwards) in emotion frequencies over time. - **Topics** uses [BERTopic](https://maartengr.github.io/BERTopic/index.html) to find topics in the datasets, and outputs a bar plot that shows the emotion distribution per topic. - """) - - - with gr.Row(): - gr.Markdown(""" - ___ - """) - with gr.Row(): - with gr.Column(): - output_markdown = gr.Markdown(""" - **Output** - """, visible=False) - - message = gr.Textbox(label="Message", visible=False) - - output_file = gr.File(label="Predictions", visible=False) - next_button_freq = gr.Button("Show emotion frequencies", visible=False) - - output_plot = gr.Plot(show_label=False, visible=False).style(container=True) - next_button_dist = gr.Button("Show emotion distribution over time", visible=False) - - output_dist = gr.Plot(show_label=False, visible=False) - next_button_peaks = gr.Button("Show peaks", visible=False) - - output_peaks = gr.Plot(show_label=False, visible=False) - next_button_topics = gr.Button("Show topics", visible=False) - - output_topics = gr.Plot(show_label=False, visible=False) - - #send_btn.click(fn=file, inputs=[input_file,input_checks], outputs=[output_file,next_button_freq,next_button_dist,next_button_peaks,next_button_topics]) - next_button_freq.click(fn=freq, inputs=[output_file,input_checks], outputs=[output_plot,next_button_dist,next_button_peaks,next_button_topics]) - next_button_dist.click(fn=dist, inputs=[output_file,input_checks], outputs=[output_dist,next_button_peaks,next_button_topics]) - next_button_peaks.click(fn=peaks, inputs=[output_file,input_checks], outputs=[output_peaks,next_button_topics]) - next_button_topics.click(fn=topics, inputs=[output_file,input_checks], outputs=output_topics) - send_btn.click(fn=unavailable, inputs=[input_file,input_checks], outputs=[output_markdown,message]) - demo_btn.click(fn=showcase, inputs=[input_file], outputs=[output_markdown,message,output_file,next_button_freq,next_button_dist,next_button_peaks,next_button_topics]) - - with gr.Row(): - with gr.Column(): - gr.Markdown(""" - Both this demo and the dataset have been created by [LT3](https://lt3.ugent.be/), the Language and Translation Technology Team of Ghent University. The EmotioNL project has been carried out with support from the Research Foundation – Flanders (FWO). For any questions, please contact luna.debruyne@ugent.be. - -
      LT3 logo FWO logo
      - """) - with gr.Column(scale=1, min_width=50): - gr.Markdown(""" - """) - -demo.launch() -#
      UGent logo LT3 logo FWO logo
      \ No newline at end of file diff --git a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/unique.h b/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/unique.h deleted file mode 100644 index 4082f5299269e77aacbae174754d57977d45ebdd..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/adl/unique.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a fill of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// the purpose of this header is to #include the unique.h header -// of the sequential, host, and device systems. It should be #included in any -// code which uses adl to dispatch unique - -#include - -// SCons can't see through the #defines below to figure out what this header -// includes, so we fake it out by specifying all possible files we might end up -// including inside an #if 0. -#if 0 -#include -#include -#include -#include -#endif - -#define __THRUST_HOST_SYSTEM_UNIQUE_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/unique.h> -#include __THRUST_HOST_SYSTEM_UNIQUE_HEADER -#undef __THRUST_HOST_SYSTEM_UNIQUE_HEADER - -#define __THRUST_DEVICE_SYSTEM_UNIQUE_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/unique.h> -#include __THRUST_DEVICE_SYSTEM_UNIQUE_HEADER -#undef __THRUST_DEVICE_SYSTEM_UNIQUE_HEADER - diff --git a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/generic/adjacent_difference.h b/spaces/ma-xu/LIVE/thrust/thrust/system/detail/generic/adjacent_difference.h deleted file mode 100644 index 6e4caaa88b904788d3a7e026bf487c01f74348e2..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/system/detail/generic/adjacent_difference.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/*! \file adjacent_difference.h - * \brief Generic implementation of adjacent_difference. - */ - -#pragma once - -#include -#include - -namespace thrust -{ -namespace system -{ -namespace detail -{ -namespace generic -{ - - -template -__host__ __device__ -OutputIterator adjacent_difference(thrust::execution_policy &exec, - InputIterator first, InputIterator last, - OutputIterator result); - - -template -__host__ __device__ -OutputIterator adjacent_difference(thrust::execution_policy &exec, - InputIterator first, InputIterator last, - OutputIterator result, - BinaryFunction binary_op); - - -} // end namespace generic -} // end namespace detail -} // end namespace system -} // end namespace thrust - -#include - diff --git a/spaces/ma-xu/LIVE/thrust/thrust/system/tbb/detail/equal.h b/spaces/ma-xu/LIVE/thrust/thrust/system/tbb/detail/equal.h deleted file mode 100644 index 13398fc9db5a02ba7cd7d2141f106fa59ba2a941..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/system/tbb/detail/equal.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// this system inherits equal -#include - diff --git a/spaces/manhkhanhUIT/BOPBTL/Global/util/image_pool.py b/spaces/manhkhanhUIT/BOPBTL/Global/util/image_pool.py deleted file mode 100644 index 1e7846e7c203f5a3d3f8d7187f906990762396fa..0000000000000000000000000000000000000000 --- a/spaces/manhkhanhUIT/BOPBTL/Global/util/image_pool.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -import random -import torch -from torch.autograd import Variable - - -class ImagePool: - def __init__(self, pool_size): - self.pool_size = pool_size - if self.pool_size > 0: - self.num_imgs = 0 - self.images = [] - - def query(self, images): - if self.pool_size == 0: - return images - return_images = [] - for image in images.data: - image = torch.unsqueeze(image, 0) - if self.num_imgs < self.pool_size: - self.num_imgs = self.num_imgs + 1 - self.images.append(image) - return_images.append(image) - else: - p = random.uniform(0, 1) - if p > 0.5: - random_id = random.randint(0, self.pool_size - 1) - tmp = self.images[random_id].clone() - self.images[random_id] = image - return_images.append(tmp) - else: - return_images.append(image) - return_images = Variable(torch.cat(return_images, 0)) - return return_images diff --git a/spaces/marker22/Bark-Voice-Cloning/setup.py b/spaces/marker22/Bark-Voice-Cloning/setup.py deleted file mode 100644 index 606849326a4002007fd42060b51e69a19c18675c..0000000000000000000000000000000000000000 --- a/spaces/marker22/Bark-Voice-Cloning/setup.py +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import setup - -setup() diff --git a/spaces/mayordp/DeepFakeAI/DeepFakeAI/uis/components/face_analyser.py b/spaces/mayordp/DeepFakeAI/DeepFakeAI/uis/components/face_analyser.py deleted file mode 100644 index 117cd3ee22c36344954ccd18c18f4fabbeeee96d..0000000000000000000000000000000000000000 --- a/spaces/mayordp/DeepFakeAI/DeepFakeAI/uis/components/face_analyser.py +++ /dev/null @@ -1,54 +0,0 @@ -from typing import Optional - -import gradio - -import DeepFakeAI.choices -import DeepFakeAI.globals -from DeepFakeAI import wording -from DeepFakeAI.uis import core as ui -from DeepFakeAI.uis.typing import Update - -FACE_ANALYSER_DIRECTION_DROPDOWN : Optional[gradio.Dropdown] = None -FACE_ANALYSER_AGE_DROPDOWN : Optional[gradio.Dropdown] = None -FACE_ANALYSER_GENDER_DROPDOWN : Optional[gradio.Dropdown] = None - - -def render() -> None: - global FACE_ANALYSER_DIRECTION_DROPDOWN - global FACE_ANALYSER_AGE_DROPDOWN - global FACE_ANALYSER_GENDER_DROPDOWN - - with gradio.Box(): - with gradio.Row(): - FACE_ANALYSER_DIRECTION_DROPDOWN = gradio.Dropdown( - label = wording.get('face_analyser_direction_dropdown_label'), - choices = DeepFakeAI.choices.face_analyser_direction, - value = DeepFakeAI.globals.face_analyser_direction - ) - FACE_ANALYSER_AGE_DROPDOWN = gradio.Dropdown( - label = wording.get('face_analyser_age_dropdown_label'), - choices = ['none'] + DeepFakeAI.choices.face_analyser_age, - value = DeepFakeAI.globals.face_analyser_age or 'none' - ) - FACE_ANALYSER_GENDER_DROPDOWN = gradio.Dropdown( - label = wording.get('face_analyser_gender_dropdown_label'), - choices = ['none'] + DeepFakeAI.choices.face_analyser_gender, - value = DeepFakeAI.globals.face_analyser_gender or 'none' - ) - ui.register_component('face_analyser_direction_dropdown', FACE_ANALYSER_DIRECTION_DROPDOWN) - ui.register_component('face_analyser_age_dropdown', FACE_ANALYSER_AGE_DROPDOWN) - ui.register_component('face_analyser_gender_dropdown', FACE_ANALYSER_GENDER_DROPDOWN) - - -def listen() -> None: - FACE_ANALYSER_DIRECTION_DROPDOWN.select(lambda value: update_dropdown('face_analyser_direction', value), inputs = FACE_ANALYSER_DIRECTION_DROPDOWN, outputs = FACE_ANALYSER_DIRECTION_DROPDOWN) - FACE_ANALYSER_AGE_DROPDOWN.select(lambda value: update_dropdown('face_analyser_age', value), inputs = FACE_ANALYSER_AGE_DROPDOWN, outputs = FACE_ANALYSER_AGE_DROPDOWN) - FACE_ANALYSER_GENDER_DROPDOWN.select(lambda value: update_dropdown('face_analyser_gender', value), inputs = FACE_ANALYSER_GENDER_DROPDOWN, outputs = FACE_ANALYSER_GENDER_DROPDOWN) - - -def update_dropdown(name : str, value : str) -> Update: - if value == 'none': - setattr(DeepFakeAI.globals, name, None) - else: - setattr(DeepFakeAI.globals, name, value) - return gradio.update(value = value) diff --git a/spaces/meowingamogus69/stable-diffusion-webui-controlnet-docker/Dockerfile b/spaces/meowingamogus69/stable-diffusion-webui-controlnet-docker/Dockerfile deleted file mode 100644 index 95dd8620e127dfa3471d2fc93e86f0918c56ee24..0000000000000000000000000000000000000000 --- a/spaces/meowingamogus69/stable-diffusion-webui-controlnet-docker/Dockerfile +++ /dev/null @@ -1,124 +0,0 @@ -FROM nvidia/cuda:11.7.1-cudnn8-devel-ubuntu22.04 - -ENV DEBIAN_FRONTEND noninteractive -ENV PYTHONUNBUFFERED=1 -ENV PIP_DISABLE_PIP_VERSION_CHECK=1 -ENV PIP_NO_CACHE_DIR=1 - -# OS setup -RUN apt-get update -y \ - && apt-get upgrade -y \ - && apt-get install -y \ - libgl1 \ - libglib2.0-0 \ - curl \ - vim \ - wget \ - git \ - git-lfs \ - tzdata \ - bash \ - ca-certificates \ - libreadline8 \ - bzip2 \ - psmisc \ - procps \ - netbase \ - openssh-client \ - libsqlite3-dev \ - python3-pip \ - python3-venv \ - python-is-python3 \ - build-essential \ - libssl-dev \ - libffi-dev \ - aria2 \ - \ - && pip3 install --upgrade pip \ - \ - && git lfs install \ - \ - && apt-get clean autoclean \ - && apt-get autoremove --yes \ - && rm -rf /var/lib/apt/lists/* - -# OS timezone setting (UTC) -RUN echo "UTC" > /etc/timezone -ENV TZ=UTC - -# Poetry for Python packages -RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/usr/local/poetry python3 - --yes \ - && ln -s /usr/local/poetry/bin/poetry /usr/bin/poetry \ - \ - && poetry config virtualenvs.create false \ - && poetry config virtualenvs.in-project false - -# Create non-root user -ENV ENV="/etc/profile" -RUN adduser --disabled-password --gecos '' user && \ - mkdir -p /app && \ - chown -R user:user /app && \ - printf "\n. /etc/profile\n" >> /home/user/.profile \ - printf "\n. /etc/profile\n" >> /home/user/.bashrc - -# Sets up virtualenv for dependencies -ENV VIRTUAL_ENV="/opt/venv" -ENV VIRTUAL_ENV_DISABLE_PROMPT=1 -ENV POETRY_ACTIVE=1 -ENV PATH="$VIRTUAL_ENV/bin:$PATH" -RUN echo "export PATH=$PATH" >> /home/user/.bashrc \ - && python3 -m venv $VIRTUAL_ENV \ - && /opt/venv/bin/pip install --upgrade --no-cache-dir pip \ - && chown -R user:user /opt/venv - -# Run as non-root user -USER user -WORKDIR /app - -# Installation of basic Python dependencies specified in pyproject.toml -COPY --chown=user:user pyproject.toml poetry.lock /app/ -RUN poetry install - -# AUTOMATIC1111' WebUI -RUN git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui /app/stable-diffusion-webui \ - && (cd /app/stable-diffusion-webui && git checkout a9fed7c364061ae6efb37f797b6b522cb3cf7aa2) - -# Deforum extension -RUN git clone https://github.com/deforum-art/deforum-for-automatic1111-webui /app/stable-diffusion-webui/extensions/deforum-for-automatic1111-webui \ - && (cd /app/stable-diffusion-webui/extensions/deforum-for-automatic1111-webui && git checkout 2366bfdb47c226df0d14e712445414e459febad3) - -# Images Browser WebUI extension -RUN git clone https://github.com/yfszzx/stable-diffusion-webui-images-browser /app/stable-diffusion-webui/extensions/stable-diffusion-webui-images-browser \ - && (cd /app/stable-diffusion-webui/extensions/stable-diffusion-webui-images-browser && git checkout a42c7a30181636a05815e62426d5eff4d3340529) - -# CiviTAI Browser WebUI extension -RUN git clone https://github.com/Vetchems/sd-civitai-browser /app/stable-diffusion-webui/extensions/sd-civitai-browser \ - && (cd /app/stable-diffusion-webui/extensions/sd-civitai-browser && git checkout b25a5daf7df3f6340d3e243d533228d8ade5288d) - -# Additional Networks WebUI extension -RUN git clone https://github.com/kohya-ss/sd-webui-additional-networks /app/stable-diffusion-webui/extensions/sd-webui-additional-networks \ - && (cd /app/stable-diffusion-webui/extensions/sd-webui-additional-networks && git checkout d2758b6c8e2e8e956865a87b31fd74d3d7c010cb) \ - && mkdir -p /app/stable-diffusion-webui/extensions/sd-webui-additional-networks/models/LoRA - -# ControlNet WebUI extension -RUN git clone https://github.com/Mikubill/sd-webui-controlnet /app/stable-diffusion-webui/extensions/sd-webui-controlnet \ - && (cd /app/stable-diffusion-webui/extensions/sd-webui-controlnet && git checkout 274dd5df217a03e059e9cf052447aece81bbd1cf) \ - && mkdir -p /app/stable-diffusion-webui/models/ControlNet - -# Prepare WebUI environment -WORKDIR /app/stable-diffusion-webui -RUN /opt/venv/bin/python launch.py --exit --skip-torch-cuda-test --xformers - -# Patch WebUI -RUN sed -i -e 's/ show_progress=False,/ show_progress=True,/g' modules/ui.py -RUN sed -i -e 's/shared.demo.launch/shared.demo.queue().launch/g' webui.py -RUN sed -i -e 's/ outputs=\[/queue=False, &/g' modules/ui.py -RUN sed -i -e 's/ queue=False, / /g' modules/ui.py - -# Copy startup scripts -COPY --chown=user:user run.py on_start.sh config.json ui-config.json shared-config.json shared-ui-config.json header_patch.py /app/stable-diffusion-webui/ -RUN chmod +x on_start.sh - -EXPOSE 7860 - -CMD ["/opt/venv/bin/python", "run.py", "--listen", "--ui-config-file", "ui-config.json", "--ui-settings-file", "config.json", "--disable-console-progressbars", "--cors-allow-origins", "huggingface.co,hf.space", "--no-progressbar-hiding", "--enable-console-prompts", "--no-download-sd-model", "--api", "--skip-version-check"] diff --git a/spaces/merve/anonymization/public/fill-in-the-blank/index.html b/spaces/merve/anonymization/public/fill-in-the-blank/index.html deleted file mode 100644 index b1ff5d0c943d3457ad18afefa53be4a9d0155f24..0000000000000000000000000000000000000000 --- a/spaces/merve/anonymization/public/fill-in-the-blank/index.html +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - - - - - - - - - - - - - What Have Language Models Learned? - - - - - - - - - - - - - - - -
      - -
      - -

      What Have Language Models Learned?

      -
      By asking language models to fill in the blank, we can probe their understanding of the world.
      -

      Large language models are making it possible for computers to write stories, program a website and turn captions into images.

      -

      One of the first of these models, BERT, is trained by taking sentences, splitting them into individual words, randomly hiding some of them, and predicting what the hidden words are. After doing this millions of times, BERT has “read” enough Shakespeare to predict how this phrase usually ends:

      -
      - -

      This page is hooked up to a version of BERT trained on Wikipedia and books.¹ Try clicking on different words to see how they’d be filled in or typing in another sentence to see what else has BERT picked up on.

      -
      - -

      Cattle or Clothes?

      -

      Besides Hamlet’s existential dread, the text BERT was trained on also contains more patterns:

      -
      - -

      Cattle and horses aren’t top purchase predictions in every state, though! In New York, some of the most likely words are clothes, books and art:

      -
      - -

      There are more than 30,000 words, punctuation marks and word fragments in BERT’s vocabulary. Every time BERT fills in a hidden word, it assigns each of them a probability. By looking at how slightly different sentences shift those probabilities, we can get a glimpse at how purchasing patterns in different places are understood.

      -
      - -

      You can edit these sentences. Or try one of these comparisons to get started:

      -

      To the extent that a computer program can “know” something, what does BERT know about where you live?

      -

      What’s in a Name?

      -

      This technique can also probe what associations BERT has learned about different groups of people. For example, it predicts people named Elsie are older than people named Lauren:

      -
      - -

      It’s also learned that people named Jim have more typically masculine jobs than people named Jane:

      -
      - -

      These aren’t just spurious correlations — Elsies really are more likely to be older than Laurens. And occupations the model associates with feminine names are held by a higher percentage of women.

      -

      Should we be concerned about these correlations? BERT was trained to fill in blanks in Wikipedia articles and books — it does a great job at that! The problem is that the internal representations of language these models have learned are used for much more – by some measures, they’re the best way we have of getting computers to understand and manipulate text.

      -

      We wouldn’t hesitate to call a conversation partner or recruiter who blithely assumed that doctors are men sexist, but that’s exactly what BERT might do if heedlessly incorporated into a chatbot or HR software:

      -
      - -

      Adjusting for assumptions like this isn’t trivial. Why machine learning systems produce a given output still isn’t well understood – determining if a credit model built on top of BERT rejected a loan application because of gender discrimation might be quite difficult.

      -

      Deploying large language models at scale also risks amplifying and perpetuating today’s harmful stereotypes. When prompted with “Two Muslims walked into a…”, for example, GPT-3 typically finishes the sentence with descriptions of violence.

      -

      How Can We Fix This?

      -

      One conceptually straightforward approach: reduce unwanted correlations from the training data to mitigate model bias.

      -

      Last year a version of BERT called Zari was trained with an additional set of generated sentences. For every sentence with a gendered noun, like boy or aunt, another sentence that replaced the noun with its gender-partner was added to the training data: in addition to “The lady doth protest too much,” Zari was also trained on “The gentleman doth protest too much.”

      -
      - -

      Unlike BERT, Zari assigns nurses and doctors an equal probability of being a “she” or a “he” after being trained on the swapped sentences. This approach hasn’t removed all the gender correlations; because names weren’t swapped, Zari’s association between masculine names and doctors has only slightly decreased from BERT’s. And the retraining doesn’t change how the model understands nonbinary gender.

      -

      Something similar happened with other attempts to remove gender bias from models’ representations of words. It’s possible to mathematically define bias and perform “brain surgery” on a model to remove it, but language is steeped in gender. Large models can have billions of parameters in which to learn stereotypes — slightly different measures of bias have found the retrained models only shifted the stereotypes around to be undetectable by the initial measure.

      -

      As with other applications of machine learning, it’s helpful to focus instead on the actual harms that could occur. Tools like AllenNLP, LMdiff and the Language Interpretability Tool make it easier to interact with language models to find where they might be falling short. Once those shortcomings are spotted, task specific mitigation measures can be simpler to apply than modifying the entire model.

      -

      It’s also possible that as models grow more capable, they might be able to explain and perform some of this debiasing themselves. Instead of forcing the model to tell us the gender of “the doctor,” we could let it respond with uncertainty that’s shown to the user and controls to override assumptions.

      -

      Credits

      -

      Adam Pearce // July 2021

      -

      Thanks to Ben Wedin, Emily Reif, James Wexler, Fernanda Viégas, Ian Tenney, Kellie Webster, Kevin Robinson, Lucas Dixon, Ludovic Peran, Martin Wattenberg, Michael Terry, Tolga Bolukbasi, Vinodkumar Prabhakaran, Xuezhi Wang, Yannick Assogba, and Zan Armstrong for their help with this piece.

      -

      Footnotes

      -

      The BERT model used on this page is the Hugging Face version of bert-large-uncased-whole-word-masking. “BERT” also refers to a type of model architecture; hundreds of BERT models have been trained and published. The model and chart code used here are available on GitHub.

      -

      Notice that “1800”, “1900” and “2000” are some of the top predictions, though. People aren’t actually more likely to be born at the start of a century, but in BERT’s training corpus of books and Wikipedia articles round numbers are more common.

      -

      Comparing BERT and Zari in this interface requires carefully tracking tokens during a transition. The BERT Difference Plots colab has ideas for extensions to systemically look at differences between the models’ output.

      -

      This analysis shouldn’t stop once a model is deployed — as language and model usage shifts, it’s important to continue studying and mitigating potential harms.

      -

      Appendix: Differences Over Time

      -

      In addition to looking at how predictions for men and women are different for a given sentence, we can also chart how those differences have changed over time:

      -
      - -

      The convergence in more recent years suggests another potential mitigation technique: using a prefix to steer the model away from unwanted correlations while preserving its understanding of natural language.

      -

      Using “In $year” as the prefix is quite limited, though, as it doesn’t handle gender-neutral pronouns and potentially increases other correlations. However, it may be possible to find a better prefix that mitigates a specific type of bias with just a couple of dozen examples.

      -
      - -

      Closer examination of these differences in differences also shows there’s a limit to the facts we can pull out of BERT this way.

      -

      Below, the top row of charts shows how predicted differences in occupations between men and women change between 1908 and 2018. The rightmost chart shows the he/she difference in 1908 against the he/she difference in 2018.

      -

      The flat slope of the rightmost chart indicates that the he/she difference has decreased for each job by about the same amount. But in reality, shifts in occupation weren’t nearly so smooth and some occupations, like accounting, switched from being majority male to majority female.

      -
      - -

      This reality-prediction mismatch could be caused by lack of training data, model size or the coarseness of the probing method. There’s an immense amount of general knowledge inside of these models — with a little bit of focused training, they can even become expert trivia players.

      -

      More Explorables

      -

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spaces/micole66/photo-chooser/README.md b/spaces/micole66/photo-chooser/README.md deleted file mode 100644 index cc17020ed249dccc2fa9c13911c08bae8abbaa56..0000000000000000000000000000000000000000 --- a/spaces/micole66/photo-chooser/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Photo Chooser -emoji: 🏢 -colorFrom: gray -colorTo: yellow -sdk: static -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/miittnnss/dcgan-image-generator/README.md b/spaces/miittnnss/dcgan-image-generator/README.md deleted file mode 100644 index c3b3968629f1b01f67baaadc7e320b099866fbf0..0000000000000000000000000000000000000000 --- a/spaces/miittnnss/dcgan-image-generator/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: DCGAN Image Generator -emoji: 🎨 -colorFrom: red -colorTo: blue -sdk: gradio -sdk_version: 3.44.4 -app_file: app.py -pinned: false -license: other ---- - -Generate images with DCGAN! \ No newline at end of file diff --git a/spaces/mikonvergence/theaTRON/src/masking.py b/spaces/mikonvergence/theaTRON/src/masking.py deleted file mode 100644 index c8d689a646ff8b2267003d2d823a48b5072d5dbc..0000000000000000000000000000000000000000 --- a/spaces/mikonvergence/theaTRON/src/masking.py +++ /dev/null @@ -1,89 +0,0 @@ -import torch -from kornia.morphology import dilation, closing -import requests -from transformers import SamModel, SamProcessor - -print('Loading SAM...') -device = "cuda" if torch.cuda.is_available() else "cpu" -model = SamModel.from_pretrained("facebook/sam-vit-huge").to(device) -processor = SamProcessor.from_pretrained("facebook/sam-vit-huge") -print('DONE') - -def build_mask(image, faces, hairs): - - # 1. Segmentation - input_points = faces # 2D location of the face - - with torch.no_grad(): - inputs = processor(image, input_points=input_points, return_tensors="pt").to(device) - outputs = model(**inputs) - - masks = processor.image_processor.post_process_masks( - outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu() - ) - scores = outputs.iou_scores - - input_points = hairs # 2D location of the face - - with torch.no_grad(): - inputs = processor(image, input_points=input_points, return_tensors="pt").to(device) - outputs = model(**inputs) - - h_masks = processor.image_processor.post_process_masks( - outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu() - ) - h_scores = outputs.iou_scores - - # 2. Post-processing - mask=masks[0][0].all(0) | h_masks[0][0].all(0) - - # dilation - tensor = mask[None,None,:,:] - kernel = torch.ones(3, 3) - mask = closing(tensor, kernel)[0,0].bool() - - return mask - -def build_mask_multi(image, faces, hairs): - - all_masks = [] - - for face,hair in zip(faces,hairs): - # 1. Segmentation - input_points = [face] # 2D location of the face - - with torch.no_grad(): - inputs = processor(image, input_points=input_points, return_tensors="pt").to(device) - outputs = model(**inputs) - - masks = processor.image_processor.post_process_masks( - outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu() - ) - scores = outputs.iou_scores - - input_points = [hair] # 2D location of the face - - with torch.no_grad(): - inputs = processor(image, input_points=input_points, return_tensors="pt").to(device) - outputs = model(**inputs) - - h_masks = processor.image_processor.post_process_masks( - outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu() - ) - h_scores = outputs.iou_scores - - # 2. Post-processing - mask=masks[0][0].all(0) | h_masks[0][0].all(0) - - # dilation - mask_T = mask[None,None,:,:] - kernel = torch.ones(3, 3) - mask = closing(mask_T, kernel)[0,0].bool() - - all_masks.append(mask) - - mask = all_masks[0] - for next_mask in all_masks[1:]: - mask = mask | next_mask - - return mask \ No newline at end of file diff --git a/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/test_time_augmentation.py b/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/test_time_augmentation.py deleted file mode 100644 index bb7a51f28419c59775013c74fdee49e5166bde51..0000000000000000000000000000000000000000 --- a/spaces/mmlab-ntu/Segment-Any-RGBD/open_vocab_seg/test_time_augmentation.py +++ /dev/null @@ -1,217 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# Copyright (c) Meta Platforms, Inc. All Rights Reserved - -import copy -from itertools import count -import math -import numpy as np -import torch -from fvcore.transforms import HFlipTransform -from torch import nn -from torch.nn.parallel import DistributedDataParallel - -from detectron2.data.detection_utils import read_image -from detectron2.modeling import DatasetMapperTTA -from detectron2.modeling.postprocessing import sem_seg_postprocess -import logging -from detectron2.utils.logger import log_every_n, log_first_n - -__all__ = [ - "SemanticSegmentorWithTTA", -] - - -class SemanticSegmentorWithTTA(nn.Module): - """ - A SemanticSegmentor with test-time augmentation enabled. - Its :meth:`__call__` method has the same interface as :meth:`SemanticSegmentor.forward`. - """ - - def __init__(self, cfg, model, tta_mapper=None, batch_size=1): - """ - Args: - cfg (CfgNode): - model (SemanticSegmentor): a SemanticSegmentor to apply TTA on. - tta_mapper (callable): takes a dataset dict and returns a list of - augmented versions of the dataset dict. Defaults to - `DatasetMapperTTA(cfg)`. - batch_size (int): batch the augmented images into this batch size for inference. - """ - super().__init__() - if isinstance(model, DistributedDataParallel): - model = model.module - self.cfg = cfg.clone() - - self.model = model - - if tta_mapper is None: - tta_mapper = DatasetMapperTTA(cfg) - self.tta_mapper = tta_mapper - self.batch_size = batch_size - - def _inference_with_model(self, inputs): - if self.cfg.TEST.SLIDING_WINDOW: - log_first_n(logging.INFO, "Using sliding window to test") - - outputs = [] - - for input in inputs: - image_size = input["image"].shape[1:] # h,w - if self.cfg.TEST.SLIDING_TILE_SIZE > 0: - tile_size = ( - self.cfg.TEST.SLIDING_TILE_SIZE, - self.cfg.TEST.SLIDING_TILE_SIZE, - ) - else: - selected_mapping = {256: 224, 512: 256, 768: 512, 896: 512} - tile_size = min(image_size) - tile_size = selected_mapping[tile_size] - tile_size = (tile_size, tile_size) - extra_info = { - k: v - for k, v in input.items() - if k not in ["image", "height", "width"] - } - log_every_n( - logging.INFO, "split {} to {}".format(image_size, tile_size) - ) - overlap = self.cfg.TEST.SLIDING_OVERLAP - stride = math.ceil(tile_size[0] * (1 - overlap)) - tile_rows = int( - math.ceil((image_size[0] - tile_size[0]) / stride) + 1 - ) # strided convolution formula - tile_cols = int(math.ceil((image_size[1] - tile_size[1]) / stride) + 1) - full_probs = None - count_predictions = None - tile_counter = 0 - - for row in range(tile_rows): - for col in range(tile_cols): - x1 = int(col * stride) - y1 = int(row * stride) - x2 = min(x1 + tile_size[1], image_size[1]) - y2 = min(y1 + tile_size[0], image_size[0]) - x1 = max( - int(x2 - tile_size[1]), 0 - ) # for portrait images the x1 underflows sometimes - y1 = max( - int(y2 - tile_size[0]), 0 - ) # for very few rows y1 underflows - - img = input["image"][:, y1:y2, x1:x2] - padded_img = nn.functional.pad( - img, - ( - 0, - tile_size[1] - img.shape[-1], - 0, - tile_size[0] - img.shape[-2], - ), - ) - tile_counter += 1 - padded_input = {"image": padded_img} - padded_input.update(extra_info) - padded_prediction = self.model([padded_input])[0]["sem_seg"] - prediction = padded_prediction[ - :, 0 : img.shape[1], 0 : img.shape[2] - ] - if full_probs is None: - full_probs = prediction.new_zeros( - prediction.shape[0], image_size[0], image_size[1] - ) - if count_predictions is None: - count_predictions = prediction.new_zeros( - prediction.shape[0], image_size[0], image_size[1] - ) - count_predictions[:, y1:y2, x1:x2] += 1 - full_probs[ - :, y1:y2, x1:x2 - ] += prediction # accumulate the predictions also in the overlapping regions - - full_probs /= count_predictions - full_probs = sem_seg_postprocess( - full_probs, - image_size, - input.get("height", image_size[0]), - input.get("width", image_size[1]), - ) - outputs.append({"sem_seg": full_probs}) - - return outputs - else: - log_first_n(logging.INFO, "Using whole image to test") - return self.model(inputs) - - def _batch_inference(self, batched_inputs): - """ - Execute inference on a list of inputs, - using batch size = self.batch_size, instead of the length of the list. - Inputs & outputs have the same format as :meth:`SemanticSegmentor.forward` - """ - outputs = [] - inputs = [] - for idx, input in zip(count(), batched_inputs): - inputs.append(input) - if len(inputs) == self.batch_size or idx == len(batched_inputs) - 1: - with torch.no_grad(): - outputs.extend(self._inference_with_model(inputs)) - inputs = [] - return outputs - - def __call__(self, batched_inputs): - """ - Same input/output format as :meth:`SemanticSegmentor.forward` - """ - - def _maybe_read_image(dataset_dict): - ret = copy.copy(dataset_dict) - if "image" not in ret: - image = read_image(ret.pop("file_name"), self.model.input_format) - image = torch.from_numpy( - np.ascontiguousarray(image.transpose(2, 0, 1)) - ) # CHW - ret["image"] = image - if "height" not in ret and "width" not in ret: - ret["height"] = image.shape[1] - ret["width"] = image.shape[2] - return ret - - return [self._inference_one_image(_maybe_read_image(x)) for x in batched_inputs] - - def _inference_one_image(self, input): - """ - Args: - input (dict): one dataset dict with "image" field being a CHW tensor - Returns: - dict: one output dict - """ - augmented_inputs, tfms = self._get_augmented_inputs(input) - # 1: forward with all augmented images - outputs = self._batch_inference(augmented_inputs) - # Delete now useless variables to avoid being out of memory - del augmented_inputs - # 2: merge the results - # handle flip specially - # outputs = [output.detach() for output in outputs] - return self._merge_auged_output(outputs, tfms) - - def _merge_auged_output(self, outputs, tfms): - new_outputs = [] - for output, tfm in zip(outputs, tfms): - if any(isinstance(t, HFlipTransform) for t in tfm.transforms): - new_outputs.append(output["sem_seg"].flip(dims=[2])) - else: - new_outputs.append(output["sem_seg"]) - del outputs - # to avoid OOM with torch.stack - final_predictions = new_outputs[0] - for i in range(1, len(new_outputs)): - final_predictions += new_outputs[i] - final_predictions = final_predictions / len(new_outputs) - del new_outputs - return {"sem_seg": final_predictions} - - def _get_augmented_inputs(self, input): - augmented_inputs = self.tta_mapper(input) - tfms = [x.pop("transforms") for x in augmented_inputs] - return augmented_inputs, tfms diff --git a/spaces/mms-meta/MMS/uroman/lib/JSON/backportPP/Boolean.pm b/spaces/mms-meta/MMS/uroman/lib/JSON/backportPP/Boolean.pm deleted file mode 100644 index 38be6a3817b3b3b5632f4ee6bd3bba7397af567e..0000000000000000000000000000000000000000 --- a/spaces/mms-meta/MMS/uroman/lib/JSON/backportPP/Boolean.pm +++ /dev/null @@ -1,27 +0,0 @@ -=head1 NAME - -JSON::PP::Boolean - dummy module providing JSON::PP::Boolean - -=head1 SYNOPSIS - - # do not "use" yourself - -=head1 DESCRIPTION - -This module exists only to provide overload resolution for Storable -and similar modules. See L for more info about this class. - -=cut - -use JSON::backportPP (); -use strict; - -1; - -=head1 AUTHOR - -This idea is from L written by -Marc Lehmann - -=cut - diff --git a/spaces/mohdelgaar/Clinical_Decisions/data.py b/spaces/mohdelgaar/Clinical_Decisions/data.py deleted file mode 100644 index 74cad52bbf9395bf33b078eba3642585591487a4..0000000000000000000000000000000000000000 --- a/spaces/mohdelgaar/Clinical_Decisions/data.py +++ /dev/null @@ -1,399 +0,0 @@ -import torch -import json -import os -import pandas as pd -import numpy as np -from torch.utils.data import Dataset, DataLoader -from transformers import AutoTokenizer -from glob import glob - -pheno_map = {'alcohol.abuse': 0, - 'advanced.lung.disease': 1, - 'advanced.heart.disease': 2, - 'chronic.pain.fibromyalgia': 3, - 'other.substance.abuse': 4, - 'psychiatric.disorders': 5, - 'obesity': 6, - 'depression': 7, - 'advanced.cancer': 8, - 'chronic.neurological.dystrophies': 9, - 'none': -1} -rev_pheno_map = {v: k for k,v in pheno_map.items()} -valid_cats = range(1,10) - -def gen_splits(args, phenos): - np.random.seed(0) - if args.task == 'token': - files = glob(os.path.join(args.data_dir, 'mimic_decisions/data/**/*')) - files = ["/".join(x.split('/')[-2:]) for x in files] - subjects = np.unique([os.path.basename(x).split('_')[0] for x in files]) - elif phenos is not None: - subjects = phenos['subject_id'].unique() - else: - raise ValueError - - phenos['phenotype_label'] = phenos['phenotype_label'].apply(lambda x: x.lower()) - - n = len(subjects) - train_count = int(0.8*n) - val_count = int(0.9*n) - int(0.8*n) - test_count = n - int(0.9*n) - - train, val, test = [], [], [] - np.random.shuffle(subjects) - subjects = list(subjects) - if args.pheno_id: - pheno_list = [rev_pheno_map[args.pheno_id]] - else: - pheno_list = list(pheno_map.keys()) - while len(subjects) > 0: - if len(pheno_list) > 0: - for pheno in pheno_list: - if len(train) < train_count: - el = None - for i, subj in enumerate(subjects): - row = phenos[phenos.subject_id == subj] - if row['phenotype_label'].apply(lambda x: pheno in x).any(): - el = subjects.pop(i) - break - if el is not None: - train.append(el) - elif el is None: - pheno_list.remove(pheno) - break - if len(val) < val_count and (not args.pheno_id or len(val) <= (0.5*val_count)): - el = None - for i, subj in enumerate(subjects): - row = phenos[phenos.subject_id == subj] - if row['phenotype_label'].apply(lambda x: pheno in x).any(): - el = subjects.pop(i) - break - if el is not None: - val.append(el) - elif el is None: - pheno_list.remove(pheno) - break - if len(test) < test_count and (not args.pheno_id or len(test) <= (0.5*test_count)): - el = None - for i, subj in enumerate(subjects): - row = phenos[phenos.subject_id == subj] - if row['phenotype_label'].apply(lambda x: pheno in x).any(): - el = subjects.pop(i) - break - if el is not None: - test.append(el) - elif el is None: - pheno_list.remove(pheno) - break - else: - if len(train) < train_count: - el = subjects.pop() - if el is not None: - train.append(el) - if len(val) < val_count: - el = subjects.pop() - if el is not None: - val.append(el) - if len(test) < test_count: - el = subjects.pop() - if el is not None: - test.append(el) - - if args.task == 'token': - train = [x for x in files if os.path.basename(x).split('_')[0] in train] - val = [x for x in files if os.path.basename(x).split('_')[0] in val] - test = [x for x in files if os.path.basename(x).split('_')[0] in test] - elif phenos is not None: - train = phenos[phenos.subject_id.isin(train)] - val = phenos[phenos.subject_id.isin(val)] - test = phenos[phenos.subject_id.isin(test)] - return train, val, test - -class MyDataset(Dataset): - def __init__(self, args, tokenizer, data_source, phenos, train = False): - super().__init__() - self.tokenizer = tokenizer - self.data = [] - self.train = train - self.pheno_ids = {k: [] for k in pheno_map.keys()} - self.dec_ids = {k: [] for k in pheno_map.keys()} - - if args.task == 'seq': - for i, row in data_source.iterrows(): - sample = self.load_phenos(args, row, i) - self.data.append(sample) - else: - for i, fn in enumerate(data_source): - sample = self.load_decisions(args, fn, i, phenos) - self.data.append(sample) - - def load_phenos(self, args, row, idx): - txt_candidates = glob(os.path.join(args.data_dir, - f'mimic_decisions/raw_text/{row["subject_id"]}_{row["hadm_id"]}*.txt')) - text = open(txt_candidates[0]).read() - - file_dir = glob(os.path.join(args.data_dir, - f'mimic_decisions/data/*/{row["subject_id"]}_{row["hadm_id"]}*.json'))[0] - with open(file_dir) as f: - data = json.load(f, strict=False) - annots = data[0]['annotations'] - - if args.text_subset: - unlabeled_text = np.ones(len(text), dtype=bool) - labeled_text = np.zeros(len(text), dtype=bool) - for annot in annots: - cat = parse_cat(annot['category']) - start, end = map(int, (annot['start_offset'], annot['end_offset'])) - if cat is not None: - unlabeled_text[start:end] = 0 - if cat in args.text_subset: - labeled_text[start:end] = 1 - - combined_text = unlabeled_text | labeled_text if args.include_nolabel else labeled_text - text = "".join([c for i,c in enumerate(text) if combined_text[i]]) - - encoding = self.tokenizer.encode_plus(text, - truncation=args.truncate_train if self.train else args.truncate_eval) - - ids = np.zeros((args.num_decs, len(encoding['input_ids']))) - for annot in annots: - start = int(annot['start_offset']) - - enc_start = encoding.char_to_token(start) - i = 1 - while enc_start is None: - enc_start = encoding.char_to_token(start+i) - i += 1 - - end = int(annot['end_offset']) - enc_end = encoding.char_to_token(end) - j = 1 - while enc_end is None: - enc_end = encoding.char_to_token(end-j) - j += 1 - - if enc_start is None or enc_end is None: - raise ValueError - - cat = parse_cat(annot['category']) - if not cat or cat not in valid_cats: - continue - ids[cat-1, enc_start:enc_end] = 1 - - labels = np.zeros(args.num_phenos) - - if args.pheno_n in (500, 800): - sample_phenos = row['phenotype_label'] - if sample_phenos != 'none': - for pheno in sample_phenos.split(','): - labels[pheno_map[pheno.lower()]] = 1 - - elif args.pheno_n == 1500: - for k,v in pheno_map.items(): - if row[k] == 1: - labels[v] = 1 - - if args.pheno_id is not None: - if args.pheno_id == -1: - labels = [0.0 if any(labels) else 1.0] - else: - labels = [labels[args.pheno_id]] - - return encoding['input_ids'], labels, ids - - def load_decisions(self, args, fn, idx, phenos): - file_dir = os.path.join(args.data_dir, 'mimic_decisions/data', fn) - - basename = os.path.basename(fn).split("-")[0] - pheno_id = "_".join(basename.split("_")[:3]) + '.txt' - txt_candidates = glob(os.path.join(args.data_dir, - f'mimic_decisions/raw_text/{basename}*.txt')) - text = open(txt_candidates[0]).read() - encoding = self.tokenizer.encode_plus(text) - if pheno_id in phenos.index: - sample_phenos = phenos.loc[pheno_id]['phenotype_label'] - for pheno in sample_phenos.split(','): - self.pheno_ids[pheno].append(idx) - - - with open(file_dir) as f: - data = json.load(f, strict=False) - annots = data[0]['annotations'] - - labels = np.zeros((len(encoding['input_ids']), args.num_labels)) - for annot in annots: - start = int(annot['start_offset']) - - enc_start = encoding.char_to_token(start) - i = 1 - while enc_start is None: - enc_start = encoding.char_to_token(start+i) - i += 1 - - end = int(annot['end_offset']) - enc_end = encoding.char_to_token(end) - j = 1 - while enc_end is None: - enc_end = encoding.char_to_token(end-j) - j += 1 - - if enc_start is None or enc_end is None: - raise ValueError - - cat = parse_cat(annot['category']) - if not cat or cat not in valid_cats: - continue - labels[enc_start:enc_end, cat-1] = 1 - return encoding['input_ids'], labels - - - def __getitem__(self, idx): - return self.data[idx] - - def __len__(self): - return len(self.data) - -def parse_cat(cat): - for i,c in enumerate(cat): - if c.isnumeric(): - if cat[i+1].isnumeric(): - return int(cat[i:i+2]) - return int(c) - return None - - -def load_phenos(args): - if args.pheno_n == 500: - phenos = pd.read_csv(os.path.join(args.data_dir, - 'mimic_decisions/phenos500'), - sep='\t').rename(lambda x: x.strip(), axis=1) - phenos['raw_text'] = phenos['raw_text'].apply(lambda x: os.path.basename(x)) - phenos[['SUBJECT_ID', 'HADM_ID', 'ROW_ID']] = \ - [os.path.splitext(x)[0].split('_')[:3] for x in phenos['raw_text']] - phenos = phenos[phenos['phenotype_label'] != '?'] - elif args.pheno_n == 800: - phenos = pd.read_csv(os.path.join(args.data_dir, 'mimic_decisions/phenos800.csv')) - phenos.rename({'Ham_ID': 'HADM_ID'}, inplace=True, axis=1) - phenos = phenos[phenos.phenotype_label != '?'] - elif args.pheno_n == 1500: - phenos = pd.read_csv(os.path.join(args.data_dir, 'mimic_decisions/phenos1500.csv')) - phenos.rename({'Hospital.Admission.ID': 'HADM_ID', - 'subject.id': 'SUBJECT_ID'}, inplace=True, axis=1) - phenos = phenos[phenos.Unsure != 1] - phenos['psychiatric.disorders'] = phenos['Dementia']\ - | phenos['Developmental.Delay.Retardation']\ - | phenos['Schizophrenia.and.other.Psychiatric.Disorders'] - else: - raise ValueError - phenos.rename(lambda k: k.lower(), inplace=True, axis = 1) - return phenos - -def downsample(dataset): - data = dataset.data - class0 = [x for x in data if x[1][0] == 0] - class1 = [x for x in data if x[1][0] == 1] - - if len(class0) > len(class1): - class0 = resample(class0, replace=False, n_samples=len(class1), random_state=0) - else: - class1 = resample(class1, replace=False, n_samples=len(class0), random_state=0) - dataset.data = class0 + class1 - -def upsample(dataset): - data = dataset.data - class0 = [x for x in data if x[1][0] == 0] - class1 = [x for x in data if x[1][0] == 1] - - if len(class0) > len(class1): - class1 = resample(class1, replace=True, n_samples=len(class0), random_state=0) - else: - class0 = resample(class0, replace=True, n_samples=len(class1), random_state=0) - dataset.data = class0 + class1 - -def load_tokenizer(name): - return AutoTokenizer.from_pretrained(name) - -def load_data(args): - from sklearn.utils import resample - def collate_segment(batch): - xs = [] - ys = [] - has_ids = len(batch[0]) == 3 - if has_ids: - idss = [] - else: - ids = None - masks = [] - for i in range(len(batch)): - x = batch[i][0] - y = batch[i][1] - if has_ids: - ids = batch[i][2] - n = len(x) - if n > args.max_len: - start = np.random.randint(0, n - args.max_len + 1) - x = x[start:start + args.max_len] - if args.task == 'token': - y = y[start:start + args.max_len] - if has_ids: - new_ids = [] - ids = [x[start:start + args.max_len] for x in ids] - for subids in ids: - subids = [idx for idx, x in enumerate(subids) if x] - new_ids.append(subids) - all_ids = set([y for x in new_ids for y in x]) - nones = set(range(args.max_len)) - all_ids - new_ids.append(list(nones)) - mask = [1] * args.max_len - else: - x = np.pad(x, (0, args.max_len - n)) - if args.task == 'token': - y = np.pad(y, ((0, args.max_len - n), (0, 0))) - mask = [1] * n + [0] * (args.max_len - n) - xs.append(x) - ys.append(y) - if has_ids: - idss.append(new_ids) - masks.append(mask) - - xs = torch.tensor(xs) - ys = torch.tensor(ys) - masks = torch.tensor(masks) - return xs, ys, ids, masks - - def collate_full(batch): - lens = [len(x[0]) for x in batch] - max_len = max(args.max_len, max(lens)) - for i in range(len(batch)): - batch[i] = list(batch[i]) - batch[i][0] = np.pad(batch[i][0], (0, max_len - lens[i])) - if args.task == 'token': - batch[i][1] = np.pad(batch[i][1], ((0, max_len - lens[i]), (0, 0))) - mask = [1] * lens[i] + [0] * (max_len - lens[i]) - batch[i].append(mask) - - return [torch.tensor(np.array([el[i] for el in batch])) for i in range(len(batch[0]))] - - phenos = load_phenos(args) - - tokenizer = load_tokenizer(args.model_name) - train_files, val_files, test_files = gen_splits(args, phenos) - args.vocab_size = tokenizer.vocab_size - args.max_length = min(tokenizer.model_max_length, 512) - - phenos.set_index('raw_text', inplace=True) - train_dataset = MyDataset(args, tokenizer, train_files, phenos, train=True) - if args.resample == 'down': - downsample(train_dataset) - elif args.resample == 'up': - upsample(train_dataset) - val_dataset = MyDataset(args, tokenizer, val_files, phenos) - test_dataset = MyDataset(args, tokenizer, test_files, phenos) - - train_dataloader = DataLoader(train_dataset, args.batch_size, True, - collate_fn=collate_segment, - ) - val_dataloader = DataLoader(val_dataset, 1, False, collate_fn=collate_full) - test_dataloader = DataLoader(test_dataset, 1, False, collate_fn=collate_full) - - return train_dataloader, val_dataloader, test_dataloader diff --git a/spaces/mshukor/UnIVAL/run_scripts/averaging/fusing/scaling_best/video/video_vqa_ofaplus_base_pretrain_s2_hsep1_shuf_el_db_initavgvideocaptionvqa.sh b/spaces/mshukor/UnIVAL/run_scripts/averaging/fusing/scaling_best/video/video_vqa_ofaplus_base_pretrain_s2_hsep1_shuf_el_db_initavgvideocaptionvqa.sh deleted file mode 100644 index 786f753369538618df348d375ce16c76c60f8911..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/run_scripts/averaging/fusing/scaling_best/video/video_vqa_ofaplus_base_pretrain_s2_hsep1_shuf_el_db_initavgvideocaptionvqa.sh +++ /dev/null @@ -1,239 +0,0 @@ - -# Number of GPUs per GPU worker -export GPUS_PER_NODE=8 -# Number of GPU workers, for single-worker training, please set to 1 -export NUM_NODES=$SLURM_NNODES -# The ip address of the rank-0 worker, for single-worker training, please set to localhost -master_addr=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1) -export MASTER_ADDR=$master_addr - -# The port for communication -export MASTER_PORT=12350 -# The rank of this worker, should be in {0, ..., WORKER_CNT-1}, for single-worker training, please set to 0 -export RANK=$SLURM_NODEID - -echo "MASTER_ADDR: $MASTER_ADDR" -echo "RANK :$RANK" -echo "NUM_NODES :$NUM_NODES" -echo "GPUS_PER_NODE :$GPUS_PER_NODE" - -export MIOPEN_USER_DB_PATH=/lus/home/NAT/gda2204/mshukor/.config/miopen_${MASTER_ADDR}_${SLURM_PROCID}/ - -echo "MIOPEN_USER_DB_PATH :$MIOPEN_USER_DB_PATH" - -num_workers=0 - - -ofa_dir=/lus/home/NAT/gda2204/mshukor/code/unival -base_data_dir=/lus/scratch/NAT/gda2204/SHARED/data -base_log_dir=/work/NAT/gda2204/mshukor/logs - - -exp_name=unival_video_vqa_initavgvideocaptionvqa - -image_dir=${base_data_dir} -data_dir=${base_data_dir}/ofa/video_data/vqa_data - -# data=${data_dir}/msrvtt_qa_train.tsv,${data_dir}/msrvtt_qa_val.tsv -data=${data_dir}/msrvtt_qa_4k_train.tsv,${data_dir}/msrvtt_qa_4k_test.tsv - - -# Note: If you have shuffled the data in advance, please uncomment the line below. -data=${data_dir}/msrvtt_qa_4k_train_1.tsv,${data_dir}/msrvtt_qa_4k_train_2.tsv,${data_dir}/msrvtt_qa_4k_train_3.tsv,${data_dir}/msrvtt_qa_4k_train_4.tsv,${data_dir}/msrvtt_qa_4k_train_5.tsv,${data_dir}/msrvtt_qa_4k_train_6.tsv,${data_dir}/msrvtt_qa_4k_train_7.tsv,${data_dir}/msrvtt_qa_4k_train_8.tsv,${data_dir}/msrvtt_qa_4k_train_9.tsv,${data_dir}/msrvtt_qa_4k_train_10.tsv,${data_dir}/msrvtt_qa_4k_test.tsv - -# ans2label_file=${base_data_dir}/ofa/video_data/vqa_data/msrvtt_trainval_ans2label.pkl -ans2label_file=${base_data_dir}/ofa/video_data/vqa_data/msrvtt_trainval_4k_ans2label.pkl - - -selected_cols=0,5,2,3,4 - - -save_base_log_dir=/lus/scratch/NAT/gda2204/SHARED/logs -save_dir=${save_base_log_dir}/ofa/checkpoints/vqa/${exp_name} -# save_dir=${base_log_dir}/ofa/checkpoints/vqa/${exp_name} -log_dir=${save_dir} - -mkdir -p $log_dir $save_dir - -restore_file=/lus/scratch/NAT/gda2204/SHARED/logs/ofa/pretrained_models/average_models/avg_vid_capvqa.pt - -lr=1e-4 - -bpe_dir=${ofa_dir}/utils/BPE -user_dir=${ofa_dir}/ofa_module - - - -task=video_vqa_gen -arch=unival_base - - -criterion=adjust_label_smoothed_encouraging_loss -label_smoothing=0.1 -batch_size=8 -valid_batch_size=8 -update_freq=2 -resnet_drop_path_rate=0.0 -encoder_drop_path_rate=0.1 -decoder_drop_path_rate=0.1 -dropout=0.1 -attention_dropout=0.0 -max_src_length=80 -max_object_length=30 -max_tgt_length=30 -num_bins=1000 -# patch_image_size=480 - -uses_ema="--uses-ema" -store_ema="--store-ema" -ema_fp32="--ema-fp32" -ema_decay=0.9999 -ema_start_update=0 - -# Specify the inference type in validation after each fine-tuning epoch -# As mentioned in the readme, you can choose from allcand or beamsearch evaluation, default to allcand -val_inference_type=beamsearch - -# Specify whether to activate unconstrained VQA finetuning, which does not use a pre-defined candidate answer set -# If --unconstrained-training is acitvated, --ans2label-file will **not be used even if it is specified** -# Meanwhile, --val-inference-type must be set to **beamsearch** -# By default, we follow the constrained finetuning as we mentioned in OFA paper, the candidate answer set shall be specified by --ans2label-file -# For more details about this option, please refer to issue #123 and PR #124 -unconstrained_training_flag="" -# unconstrained_training_flag="--unconstrained-training" - - - -### -image_encoder_name=timm_resnet #vit_base_patch16_224 -patch_image_size=480 -resnet_type=resnet101 - -resnet_model_path=${base_log_dir}/pretrained_models/resnet101-5d3b4d8f.pth - -# video -video_encoder_name=all_resnext101 -patch_frame_size=384 -video_model_path=${base_log_dir}/pretrained_models/3dcnn/resnext-101-kinetics.pth #${base_log_dir}/pretrained_models/TimeSformer_divST_8x32_224_K600.pyth -num_frames=8 - -eval_args='--eval-args={"beam":5,"unnormalized":true,"temperature":1.0,"stop_on_max_len":true}' - - -sample_patch_num='--sample-patch-num=784' # '' - -save_interval_updates=0 -validate_interval_updates=2000 - -drop_worst_ratio=0.05 # modified from 0.2 for el -log_end=0.75 # for el -drop_best_ratio=0.05 -drop_best_after=6000 -drop_worst_after=6000 - - -for max_epoch in {35,}; do - echo "max_epoch "${max_epoch} - for warmup_ratio in {0.04,}; do - echo "warmup_updates "${warmup_updates} - for lr in {$lr,}; do - echo "lr "${lr} - for patch_image_size in {$patch_image_size,}; do - echo "patch_image_size "${patch_image_size} - - log_file=${log_dir}/${max_epoch}"_"${warmup_ratio}"_"${lr}"_"${patch_image_size}"_rank"${RANK}".log" - save_path=${save_dir}/${max_epoch}"_"${warmup_ratio}"_"${lr}"_"${patch_image_size} - mkdir -p $save_path - - python3 -m torch.distributed.launch \ - --nnodes=${NUM_NODES} \ - --nproc_per_node=${GPUS_PER_NODE} \ - --master_port=${MASTER_PORT} \ - --node_rank=${RANK} \ - --master_addr=${MASTER_ADDR} \ - --use_env ${ofa_dir}/train.py \ - ${data} \ - --selected-cols=${selected_cols} \ - --bpe-dir=${bpe_dir} \ - --user-dir=${user_dir} \ - --restore-file=${restore_file} \ - --save-dir=${save_path} \ - --task=${task} \ - --arch=${arch} \ - --criterion=${criterion} \ - --label-smoothing=${label_smoothing} \ - --batch-size=${batch_size} \ - --update-freq=${update_freq} \ - --encoder-normalize-before \ - --decoder-normalize-before \ - --share-decoder-input-output-embed \ - --share-all-embeddings \ - --layernorm-embedding \ - --patch-layernorm-embedding \ - --code-layernorm-embedding \ - --resnet-drop-path-rate=${resnet_drop_path_rate} \ - --encoder-drop-path-rate=${encoder_drop_path_rate} \ - --decoder-drop-path-rate=${decoder_drop_path_rate} \ - --dropout=${dropout} \ - --attention-dropout=${attention_dropout} \ - --weight-decay=0.01 \ - --optimizer=adam \ - --adam-betas="(0.9,0.999)" \ - --adam-eps=1e-08 \ - --clip-norm=1.0 \ - --lr-scheduler=polynomial_decay \ - --lr=${lr} \ - --max-epoch=${max_epoch} \ - --warmup-ratio=${warmup_ratio} \ - --log-format=simple \ - --log-interval=10 \ - --fixed-validation-seed=7 \ - --keep-best-checkpoints=1 \ - --no-epoch-checkpoints \ - --save-interval=1 --validate-interval=1 --validate-interval-updates=${validate_interval_updates} \ - --save-interval-updates=${save_interval_updates} \ - --best-checkpoint-metric=vqa_score --maximize-best-checkpoint-metric \ - --max-src-length=${max_src_length} \ - --max-object-length=${max_object_length} \ - --max-tgt-length=${max_tgt_length} \ - --find-unused-parameters \ - --freeze-encoder-embedding \ - --freeze-decoder-embedding \ - ${unconstrained_training_flag} \ - --ans2label-file=${ans2label_file} \ - --valid-batch-size=${valid_batch_size} \ - --add-type-embedding \ - --scale-attn \ - --scale-fc \ - --scale-heads \ - --disable-entangle \ - --num-bins=${num_bins} \ - --patch-image-size=${patch_image_size} \ - --prompt-type=prev_output \ - --fp16 \ - --fp16-scale-window=512 \ - ${uses_ema} \ - ${store_ema} \ - ${ema_fp32} \ - --ema-decay=${ema_decay} \ - --ema-start-update=${ema_start_update} \ - --val-inference-type=${val_inference_type} \ - --num-workers=0 \ - --image-encoder-name=${image_encoder_name} \ - --image-dir=${image_dir} \ - --video-encoder-name=${video_encoder_name} \ - --video-model-path=${video_model_path} \ - --patch-frame-size=${patch_frame_size} \ - --num-frames=${num_frames} \ - ${sample_patch_num} \ - ${eval_args} \ - --resnet-type=${resnet_type} \ - --resnet-model-path=${resnet_model_path} \ - --log-end ${log_end} --drop-best-ratio ${drop_best_ratio} --drop-best-after ${drop_best_after} \ - --drop-worst-ratio ${drop_worst_ratio} --drop-worst-after ${drop_worst_after} \ - --reset-dataloader --reset-meters --reset-optimizer - - done - done - done -done diff --git a/spaces/multimodalart/dreambooth-training/train_dreambooth.py b/spaces/multimodalart/dreambooth-training/train_dreambooth.py deleted file mode 100644 index f4ff135e549f0d6c72f733092f3df817cb178e01..0000000000000000000000000000000000000000 --- a/spaces/multimodalart/dreambooth-training/train_dreambooth.py +++ /dev/null @@ -1,889 +0,0 @@ -import argparse -import itertools -import math -import os -from pathlib import Path -from typing import Optional -import subprocess -import sys -import gc -import random - -import torch -import torch.nn.functional as F -import torch.utils.checkpoint -from torch.utils.data import Dataset - -from accelerate import Accelerator -from accelerate.logging import get_logger -from accelerate.utils import set_seed -from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel -from diffusers.utils.import_utils import is_xformers_available -from diffusers.optimization import get_scheduler -from huggingface_hub import HfFolder, Repository, whoami -from PIL import Image -from torchvision import transforms -from tqdm.auto import tqdm -from transformers import CLIPTextModel, CLIPTokenizer - - -logger = get_logger(__name__) - - -def parse_args(): - parser = argparse.ArgumentParser(description="Simple example of a training script.") - parser.add_argument( - "--pretrained_model_name_or_path", - type=str, - default=None, - #required=True, - help="Path to pretrained model or model identifier from huggingface.co/models.", - ) - parser.add_argument( - "--tokenizer_name", - type=str, - default=None, - help="Pretrained tokenizer name or path if not the same as model_name", - ) - parser.add_argument( - "--instance_data_dir", - type=str, - default=None, - #required=True, - help="A folder containing the training data of instance images.", - ) - parser.add_argument( - "--class_data_dir", - type=str, - default=None, - #required=False, - help="A folder containing the training data of class images.", - ) - parser.add_argument( - "--instance_prompt", - type=str, - default=None, - help="The prompt with identifier specifying the instance", - ) - parser.add_argument( - "--class_prompt", - type=str, - default="", - help="The prompt to specify images in the same class as provided instance images.", - ) - parser.add_argument( - "--with_prior_preservation", - default=False, - action="store_true", - help="Flag to add prior preservation loss.", - ) - parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.") - parser.add_argument( - "--num_class_images", - type=int, - default=100, - help=( - "Minimal class images for prior preservation loss. If not have enough images, additional images will be" - " sampled with class_prompt." - ), - ) - parser.add_argument( - "--output_dir", - type=str, - default="", - help="The output directory where the model predictions and checkpoints will be written.", - ) - parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") - parser.add_argument( - "--resolution", - type=int, - default=512, - help=( - "The resolution for input images, all the images in the train/validation dataset will be resized to this" - " resolution" - ), - ) - parser.add_argument( - "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution" - ) - parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder") - parser.add_argument( - "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader." - ) - parser.add_argument( - "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images." - ) - parser.add_argument("--num_train_epochs", type=int, default=1) - parser.add_argument( - "--max_train_steps", - type=int, - default=None, - help="Total number of training steps to perform. If provided, overrides num_train_epochs.", - ) - parser.add_argument( - "--gradient_accumulation_steps", - type=int, - default=1, - help="Number of updates steps to accumulate before performing a backward/update pass.", - ) - parser.add_argument( - "--gradient_checkpointing", - action="store_true", - help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.", - ) - parser.add_argument( - "--learning_rate", - type=float, - default=5e-6, - help="Initial learning rate (after the potential warmup period) to use.", - ) - parser.add_argument( - "--scale_lr", - action="store_true", - default=False, - help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.", - ) - parser.add_argument( - "--lr_scheduler", - type=str, - default="constant", - help=( - 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",' - ' "constant", "constant_with_warmup"]' - ), - ) - parser.add_argument( - "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler." - ) - parser.add_argument( - "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes." - ) - parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.") - parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.") - parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.") - parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer") - parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") - parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") - parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.") - parser.add_argument( - "--hub_model_id", - type=str, - default=None, - help="The name of the repository to keep in sync with the local `output_dir`.", - ) - parser.add_argument( - "--logging_dir", - type=str, - default="logs", - help=( - "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to" - " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***." - ), - ) - parser.add_argument( - "--mixed_precision", - type=str, - default="no", - choices=["no", "fp16", "bf16"], - help=( - "Whether to use mixed precision. Choose" - "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." - "and an Nvidia Ampere GPU." - ), - ) - - parser.add_argument( - "--save_n_steps", - type=int, - default=1, - help=("Save the model every n global_steps"), - ) - - - parser.add_argument( - "--save_starting_step", - type=int, - default=1, - help=("The step from which it starts saving intermediary checkpoints"), - ) - - parser.add_argument( - "--stop_text_encoder_training", - type=int, - default=1000000, - help=("The step at which the text_encoder is no longer trained"), - ) - - - parser.add_argument( - "--image_captions_filename", - action="store_true", - help="Get captions from filename", - ) - - - parser.add_argument( - "--dump_only_text_encoder", - action="store_true", - default=False, - help="Dump only text encoder", - ) - - parser.add_argument( - "--train_only_unet", - action="store_true", - default=False, - help="Train only the unet", - ) - - parser.add_argument( - "--cache_latents", - action="store_true", - default=False, - help="Train only the unet", - ) - - parser.add_argument( - "--Session_dir", - type=str, - default="", - help="Current session directory", - ) - - - - - parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") - - args = parser.parse_args() - env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) - if env_local_rank != -1 and env_local_rank != args.local_rank: - args.local_rank = env_local_rank - - #if args.instance_data_dir is None: - # raise ValueError("You must specify a train data directory.") - - #if args.with_prior_preservation: - # if args.class_data_dir is None: - # raise ValueError("You must specify a data directory for class images.") - # if args.class_prompt is None: - # raise ValueError("You must specify prompt for class images.") - - return args - - -class DreamBoothDataset(Dataset): - """ - A dataset to prepare the instance and class images with the prompts for fine-tuning the model. - It pre-processes the images and the tokenizes prompts. - """ - - def __init__( - self, - instance_data_root, - instance_prompt, - tokenizer, - args, - class_data_root=None, - class_prompt=None, - size=512, - center_crop=False, - ): - self.size = size - self.center_crop = center_crop - self.tokenizer = tokenizer - self.image_captions_filename = None - - self.instance_data_root = Path(instance_data_root) - if not self.instance_data_root.exists(): - raise ValueError("Instance images root doesn't exists.") - - self.instance_images_path = list(Path(instance_data_root).iterdir()) - self.num_instance_images = len(self.instance_images_path) - self.instance_prompt = instance_prompt - self._length = self.num_instance_images - - if args.image_captions_filename: - self.image_captions_filename = True - - if class_data_root is not None: - self.class_data_root = Path(class_data_root) - self.class_data_root.mkdir(parents=True, exist_ok=True) - self.class_images_path = list(self.class_data_root.iterdir()) - random.shuffle(self.class_images_path) - self.num_class_images = len(self.class_images_path) - self._length = max(self.num_class_images, self.num_instance_images) - self.class_prompt = class_prompt - else: - self.class_data_root = None - - self.image_transforms = transforms.Compose( - [ - transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR), - transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size), - transforms.ToTensor(), - transforms.Normalize([0.5], [0.5]), - ] - ) - - def __len__(self): - return self._length - - def __getitem__(self, index): - example = {} - path = self.instance_images_path[index % self.num_instance_images] - instance_image = Image.open(path) - if not instance_image.mode == "RGB": - instance_image = instance_image.convert("RGB") - - instance_prompt = self.instance_prompt - - if self.image_captions_filename: - filename = Path(path).stem - pt=''.join([i for i in filename if not i.isdigit()]) - pt=pt.replace("_"," ") - pt=pt.replace("(","") - pt=pt.replace(")","") - pt=pt.replace("-","") - instance_prompt = pt - sys.stdout.write(" " +instance_prompt+" ") - sys.stdout.flush() - - - example["instance_images"] = self.image_transforms(instance_image) - example["instance_prompt_ids"] = self.tokenizer( - instance_prompt, - padding="do_not_pad", - truncation=True, - max_length=self.tokenizer.model_max_length, - ).input_ids - - if self.class_data_root: - class_image = Image.open(self.class_images_path[index % self.num_class_images]) - if not class_image.mode == "RGB": - class_image = class_image.convert("RGB") - example["class_images"] = self.image_transforms(class_image) - example["class_prompt_ids"] = self.tokenizer( - self.class_prompt, - padding="do_not_pad", - truncation=True, - max_length=self.tokenizer.model_max_length, - ).input_ids - - return example - - - -class PromptDataset(Dataset): - "A simple dataset to prepare the prompts to generate class images on multiple GPUs." - - def __init__(self, prompt, num_samples): - self.prompt = prompt - self.num_samples = num_samples - - def __len__(self): - return self.num_samples - - def __getitem__(self, index): - example = {} - example["prompt"] = self.prompt - example["index"] = index - return example - -class LatentsDataset(Dataset): - def __init__(self, latents_cache, text_encoder_cache): - self.latents_cache = latents_cache - self.text_encoder_cache = text_encoder_cache - - def __len__(self): - return len(self.latents_cache) - - def __getitem__(self, index): - return self.latents_cache[index], self.text_encoder_cache[index] - -def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None): - if token is None: - token = HfFolder.get_token() - if organization is None: - username = whoami(token)["name"] - return f"{username}/{model_id}" - else: - return f"{organization}/{model_id}" - -def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict: - """ - Starts from base starting dict and then adds the remaining key values from updater replacing the values from - the first starting/base dict with the second updater dict. - - For later: how does d = {**d1, **d2} replace collision? - - :param starting_dict: - :param updater_dict: - :return: - """ - new_dict: dict = starting_dict.copy() # start with keys and values of starting_dict - new_dict.update(updater_dict) # modifies starting_dict with keys and values of updater_dict - return new_dict - -def merge_args(args1: argparse.Namespace, args2: argparse.Namespace) -> argparse.Namespace: - """ - - ref: https://stackoverflow.com/questions/56136549/how-can-i-merge-two-argparse-namespaces-in-python-2-x - :param args1: - :param args2: - :return: - """ - # - the merged args - # The vars() function returns the __dict__ attribute to values of the given object e.g {field:value}. - merged_key_values_for_namespace: dict = merge_two_dicts(vars(args1), vars(args2)) - args = argparse.Namespace(**merged_key_values_for_namespace) - return args - -def run_training(args_imported): - args_default = parse_args() - args = merge_args(args_default, args_imported) - print(args) - logging_dir = Path(args.output_dir, args.logging_dir) - i=args.save_starting_step - accelerator = Accelerator( - gradient_accumulation_steps=args.gradient_accumulation_steps, - mixed_precision=args.mixed_precision, - log_with="tensorboard", - logging_dir=logging_dir, - ) - - # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate - # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models. - # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate. - if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1: - raise ValueError( - "Gradient accumulation is not supported when training the text encoder in distributed training. " - "Please set gradient_accumulation_steps to 1. This feature will be supported in the future." - ) - - if args.seed is not None: - set_seed(args.seed) - - if args.with_prior_preservation: - class_images_dir = Path(args.class_data_dir) - if not class_images_dir.exists(): - class_images_dir.mkdir(parents=True) - cur_class_images = len(list(class_images_dir.iterdir())) - - if cur_class_images < args.num_class_images: - torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32 - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, torch_dtype=torch_dtype - ) - pipeline.set_progress_bar_config(disable=True) - - num_new_images = args.num_class_images - cur_class_images - logger.info(f"Number of class images to sample: {num_new_images}.") - - sample_dataset = PromptDataset(args.class_prompt, num_new_images) - sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size) - - sample_dataloader = accelerator.prepare(sample_dataloader) - pipeline.to(accelerator.device) - - for example in tqdm( - sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process - ): - with torch.autocast("cuda"): - images = pipeline(example["prompt"]).images - - for i, image in enumerate(images): - image.save(class_images_dir / f"{example['index'][i] + cur_class_images}.jpg") - - del pipeline - if torch.cuda.is_available(): - torch.cuda.empty_cache() - - # Handle the repository creation - if accelerator.is_main_process: - if args.push_to_hub: - if args.hub_model_id is None: - repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token) - else: - repo_name = args.hub_model_id - repo = Repository(args.output_dir, clone_from=repo_name) - - with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore: - if "step_*" not in gitignore: - gitignore.write("step_*\n") - if "epoch_*" not in gitignore: - gitignore.write("epoch_*\n") - elif args.output_dir is not None: - os.makedirs(args.output_dir, exist_ok=True) - - # Load the tokenizer - if args.tokenizer_name: - tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name) - elif args.pretrained_model_name_or_path: - tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer") - - # Load models and create wrapper for stable diffusion - if args.train_only_unet: - if os.path.exists(str(args.output_dir+"/text_encoder_trained")): - text_encoder = CLIPTextModel.from_pretrained(args.output_dir, subfolder="text_encoder_trained") - elif os.path.exists(str(args.output_dir+"/text_encoder")): - text_encoder = CLIPTextModel.from_pretrained(args.output_dir, subfolder="text_encoder") - else: - text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") - else: - text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") - vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae") - unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet") - if is_xformers_available(): - try: - print("Enabling memory efficient attention with xformers...") - unet.enable_xformers_memory_efficient_attention() - except Exception as e: - logger.warning( - f"Could not enable memory efficient attention. Make sure xformers is installed correctly and a GPU is available: {e}" - ) - vae.requires_grad_(False) - if not args.train_text_encoder: - text_encoder.requires_grad_(False) - - if args.gradient_checkpointing: - unet.enable_gradient_checkpointing() - if args.train_text_encoder: - text_encoder.gradient_checkpointing_enable() - - if args.scale_lr: - args.learning_rate = ( - args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes - ) - - # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs - if args.use_8bit_adam: - try: - import bitsandbytes as bnb - except ImportError: - raise ImportError( - "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`." - ) - - optimizer_class = bnb.optim.AdamW8bit - else: - optimizer_class = torch.optim.AdamW - - params_to_optimize = ( - itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters() - ) - optimizer = optimizer_class( - params_to_optimize, - lr=args.learning_rate, - betas=(args.adam_beta1, args.adam_beta2), - weight_decay=args.adam_weight_decay, - eps=args.adam_epsilon, - ) - - noise_scheduler = DDPMScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler") - - train_dataset = DreamBoothDataset( - instance_data_root=args.instance_data_dir, - instance_prompt=args.instance_prompt, - class_data_root=args.class_data_dir if args.with_prior_preservation else None, - class_prompt=args.class_prompt, - tokenizer=tokenizer, - size=args.resolution, - center_crop=args.center_crop, - args=args, - ) - - def collate_fn(examples): - input_ids = [example["instance_prompt_ids"] for example in examples] - pixel_values = [example["instance_images"] for example in examples] - - # Concat class and instance examples for prior preservation. - # We do this to avoid doing two forward passes. - if args.with_prior_preservation: - input_ids += [example["class_prompt_ids"] for example in examples] - pixel_values += [example["class_images"] for example in examples] - - pixel_values = torch.stack(pixel_values) - pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float() - - input_ids = tokenizer.pad({"input_ids": input_ids}, padding=True, return_tensors="pt").input_ids - - batch = { - "input_ids": input_ids, - "pixel_values": pixel_values, - } - return batch - - train_dataloader = torch.utils.data.DataLoader( - train_dataset, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn - ) - - # Scheduler and math around the number of training steps. - overrode_max_train_steps = False - num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) - if args.max_train_steps is None: - args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch - overrode_max_train_steps = True - - lr_scheduler = get_scheduler( - args.lr_scheduler, - optimizer=optimizer, - num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps, - num_training_steps=args.max_train_steps * args.gradient_accumulation_steps, - ) - - if args.train_text_encoder: - unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( - unet, text_encoder, optimizer, train_dataloader, lr_scheduler - ) - else: - unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( - unet, optimizer, train_dataloader, lr_scheduler - ) - - weight_dtype = torch.float32 - if args.mixed_precision == "fp16": - weight_dtype = torch.float16 - elif args.mixed_precision == "bf16": - weight_dtype = torch.bfloat16 - - # Move text_encode and vae to gpu. - # For mixed precision training we cast the text_encoder and vae weights to half-precision - # as these models are only used for inference, keeping weights in full precision is not required. - vae.to(accelerator.device, dtype=weight_dtype) - if not args.train_text_encoder: - text_encoder.to(accelerator.device, dtype=weight_dtype) - - - if args.cache_latents: - latents_cache = [] - text_encoder_cache = [] - for batch in tqdm(train_dataloader, desc="Caching latents"): - with torch.no_grad(): - batch["pixel_values"] = batch["pixel_values"].to(accelerator.device, non_blocking=True, dtype=weight_dtype) - batch["input_ids"] = batch["input_ids"].to(accelerator.device, non_blocking=True) - latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist) - if args.train_text_encoder: - text_encoder_cache.append(batch["input_ids"]) - else: - text_encoder_cache.append(text_encoder(batch["input_ids"])[0]) - train_dataset = LatentsDataset(latents_cache, text_encoder_cache) - train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, collate_fn=lambda x: x, shuffle=True) - - del vae - #if not args.train_text_encoder: - # del text_encoder - if torch.cuda.is_available(): - torch.cuda.empty_cache() - - # We need to recalculate our total training steps as the size of the training dataloader may have changed. - num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) - if overrode_max_train_steps: - args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch - # Afterwards we recalculate our number of training epochs - args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) - - # We need to initialize the trackers we use, and also store our configuration. - # The trackers initializes automatically on the main process. - if accelerator.is_main_process: - accelerator.init_trackers("dreambooth", config=vars(args)) - - def bar(prg): - br='|'+'█' * prg + ' ' * (25-prg)+'|' - return br - - # Train! - total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps - - logger.info("***** Running training *****") - logger.info(f" Num examples = {len(train_dataset)}") - logger.info(f" Num batches each epoch = {len(train_dataloader)}") - logger.info(f" Num Epochs = {args.num_train_epochs}") - logger.info(f" Instantaneous batch size per device = {args.train_batch_size}") - logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") - logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") - logger.info(f" Total optimization steps = {args.max_train_steps}") - # Only show the progress bar once on each machine. - progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) - global_step = 0 - - for epoch in range(args.num_train_epochs): - unet.train() - if args.train_text_encoder: - text_encoder.train() - for step, batch in enumerate(train_dataloader): - with accelerator.accumulate(unet): - # Convert images to latent space - with torch.no_grad(): - if args.cache_latents: - latents_dist = batch[0][0] - else: - latents_dist = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist - latents = latents_dist.sample() * 0.18215 - - # Sample noise that we'll add to the latents - noise = torch.randn_like(latents) - bsz = latents.shape[0] - # Sample a random timestep for each image - timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device) - timesteps = timesteps.long() - - # Add noise to the latents according to the noise magnitude at each timestep - # (this is the forward diffusion process) - noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps) - - # Get the text embedding for conditioning - if(args.cache_latents): - if args.train_text_encoder: - encoder_hidden_states = text_encoder(batch[0][1])[0] - else: - encoder_hidden_states = batch[0][1] - else: - encoder_hidden_states = text_encoder(batch["input_ids"])[0] - - # Predict the noise residual - model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample - - # Get the target for loss depending on the prediction type - if noise_scheduler.config.prediction_type == "epsilon": - target = noise - elif noise_scheduler.config.prediction_type == "v_prediction": - target = noise_scheduler.get_velocity(latents, noise, timesteps) - else: - raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}") - - if args.with_prior_preservation: - # Chunk the noise and model_pred into two parts and compute the loss on each part separately. - model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0) - target, target_prior = torch.chunk(target, 2, dim=0) - - # Compute instance loss - loss = F.mse_loss(model_pred.float(), target.float(), reduction="none").mean([1, 2, 3]).mean() - - # Compute prior loss - prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean") - - # Add the prior loss to the instance loss. - loss = loss + args.prior_loss_weight * prior_loss - else: - loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") - - accelerator.backward(loss) - if accelerator.sync_gradients: - params_to_clip = ( - itertools.chain(unet.parameters(), text_encoder.parameters()) - if args.train_text_encoder - else unet.parameters() - ) - accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm) - optimizer.step() - lr_scheduler.step() - optimizer.zero_grad() - - # Checks if the accelerator has performed an optimization step behind the scenes - if accelerator.sync_gradients: - progress_bar.update(1) - global_step += 1 - - fll=round((global_step*100)/args.max_train_steps) - fll=round(fll/4) - pr=bar(fll) - - logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]} - progress_bar.set_postfix(**logs) - progress_bar.set_description_str("Progress:"+pr) - accelerator.log(logs, step=global_step) - - if global_step >= args.max_train_steps: - break - - if args.train_text_encoder and global_step == args.stop_text_encoder_training and global_step >= 30: - if accelerator.is_main_process: - print(" " +" Freezing the text_encoder ..."+" ") - frz_dir=args.output_dir + "/text_encoder_frozen" - if os.path.exists(frz_dir): - subprocess.call('rm -r '+ frz_dir, shell=True) - os.mkdir(frz_dir) - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - unet=accelerator.unwrap_model(unet), - text_encoder=accelerator.unwrap_model(text_encoder), - ) - pipeline.text_encoder.save_pretrained(frz_dir) - - if args.save_n_steps >= 200: - if global_step < args.max_train_steps and global_step+1==i: - ckpt_name = "_step_" + str(global_step+1) - save_dir = Path(args.output_dir+ckpt_name) - save_dir=str(save_dir) - save_dir=save_dir.replace(" ", "_") - if not os.path.exists(save_dir): - os.mkdir(save_dir) - inst=save_dir[16:] - inst=inst.replace(" ", "_") - print(" SAVING CHECKPOINT: "+args.Session_dir+"/"+inst+".ckpt") - # Create the pipeline using the trained modules and save it. - if accelerator.is_main_process: - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - unet=accelerator.unwrap_model(unet), - text_encoder=accelerator.unwrap_model(text_encoder), - ) - pipeline.save_pretrained(save_dir) - frz_dir=args.output_dir + "/text_encoder_frozen" - if args.train_text_encoder and os.path.exists(frz_dir): - subprocess.call('rm -r '+save_dir+'/text_encoder/*.*', shell=True) - subprocess.call('cp -f '+frz_dir +'/*.* '+ save_dir+'/text_encoder', shell=True) - chkpth=args.Session_dir+"/"+inst+".ckpt" - subprocess.call('python /content/diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py --model_path ' + save_dir + ' --checkpoint_path ' + chkpth + ' --half', shell=True) - subprocess.call('rm -r '+ save_dir, shell=True) - i=i+args.save_n_steps - - accelerator.wait_for_everyone() - - # Create the pipeline using using the trained modules and save it. - if accelerator.is_main_process: - if args.dump_only_text_encoder: - txt_dir=args.output_dir + "/text_encoder_trained" - if not os.path.exists(txt_dir): - os.mkdir(txt_dir) - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - unet=accelerator.unwrap_model(unet), - text_encoder=accelerator.unwrap_model(text_encoder), - ) - pipeline.text_encoder.save_pretrained(txt_dir) - - elif args.train_only_unet: - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - unet=accelerator.unwrap_model(unet), - text_encoder=accelerator.unwrap_model(text_encoder), - ) - pipeline.save_pretrained(args.output_dir) - txt_dir=args.output_dir + "/text_encoder_trained" - subprocess.call('rm -r '+txt_dir, shell=True) - - else: - pipeline = StableDiffusionPipeline.from_pretrained( - args.pretrained_model_name_or_path, - unet=accelerator.unwrap_model(unet), - text_encoder=accelerator.unwrap_model(text_encoder), - ) - frz_dir=args.output_dir + "/text_encoder_frozen" - pipeline.save_pretrained(args.output_dir) - if args.train_text_encoder and os.path.exists(frz_dir): - subprocess.call('mv -f '+frz_dir +'/*.* '+ args.output_dir+'/text_encoder', shell=True) - subprocess.call('rm -r '+ frz_dir, shell=True) - - if args.push_to_hub: - repo.push_to_hub(commit_message="End of training", blocking=False, auto_lfs_prune=True) - - accelerator.end_training() - del pipeline - torch.cuda.empty_cache() - gc.collect() -if __name__ == "__main__": - pass - #main() - diff --git a/spaces/ncats/EpiPipeline4RD/EpiExtract4GARD-v2/READ.md b/spaces/ncats/EpiPipeline4RD/EpiExtract4GARD-v2/READ.md deleted file mode 100644 index 2282fafc6ff5e57aa41fb6d5aac030d209a79df4..0000000000000000000000000000000000000000 --- a/spaces/ncats/EpiPipeline4RD/EpiExtract4GARD-v2/READ.md +++ /dev/null @@ -1 +0,0 @@ -This is a mirror of [this model](https://huggingface.co/ncats/EpiExtract4GARD-v2) to speed up Space building process. \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Cloud Mining Free Ghs Mining Calculator For Bitcoin !!HOT!!.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Cloud Mining Free Ghs Mining Calculator For Bitcoin !!HOT!!.md deleted file mode 100644 index 05fbb7eb9ca7250b91bb5649b6a2efb68ee156f7..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Cloud Mining Free Ghs Mining Calculator For Bitcoin !!HOT!!.md +++ /dev/null @@ -1,48 +0,0 @@ - -```markdown -

      How to Mine Bitcoin for Free with Cloud Mining

      - -

      Bitcoin mining is a process of creating new bitcoins by solving complex mathematical problems. Bitcoin miners use specialized hardware and software to verify and secure transactions on the Bitcoin network. However, Bitcoin mining is not easy and requires a lot of investment, technical knowledge, and electricity.

      - -

      Fortunately, there is a way to mine Bitcoin without buying expensive equipment or paying high electricity bills. This method is called cloud mining, and it allows you to rent mining power from a remote data center that runs the mining hardware and software for you. You pay a fee to the cloud mining provider and receive a share of the mining rewards in return.

      -

      Cloud Mining Free Ghs Mining Calculator For Bitcoin


      Download ››››› https://urlcod.com/2uIb7e



      - -

      Cloud mining is a popular option for people who want to get involved in Bitcoin mining without the hassle and risk of running their own hardware. However, not all cloud mining providers are trustworthy and profitable. Some of them may charge hidden fees, offer low returns, or even run scams.

      - -

      That's why some people look for free cloud mining services that offer free or low-cost entry plans to start mining Bitcoin. These services may provide some initial funds, bonuses, or referrals to help you boost your mining income. However, free cloud mining also comes with its own drawbacks, such as lower payouts, limited features, or higher difficulty levels.

      -

      - -

      In this article, we will review some of the best free cloud mining providers that you can choose from. We will also explain how to use a cloud mining calculator to estimate your potential earnings and how to avoid scams and frauds in the cloud mining industry.

      - -

      Best Free Cloud Mining Providers

      - -

      Here are some of the most reputable and reliable free cloud mining providers that you can try:

      - -
        -
      • StormGain: StormGain is a crypto trading platform that also offers a free cloud mining app for your Android or iOS device. You don't need any equipment or technical skills to start mining with StormGain. The app claims to not drain your battery or use up any CPU power. You can earn up to 0.03 BTC per day with StormGain's cloud mining app. You can withdraw your earnings once they reach 10 USDT in Bitcoin. StormGain is a member of the Blockchain Association of the Financial Commission, which verifies its legitimacy and security.
      • -
      • IQ Mining: IQ Mining is a cloud mining platform that supports various cryptocurrencies, including Bitcoin. IQ Mining offers different plans based on your hash rate speed and contract duration. You can start with as low as $200 for a 1-year contract with 10 TH/s of hash rate. IQ Mining claims to provide daily payouts, smart mining features, and up to 300% return on investment. IQ Mining also has a referral program that allows you to earn up to 10% commission from your referrals' purchases.
      • -
      • ECOS: ECOS is a cloud mining platform that operates in Armenia, where it has its own mining farm and a free economic zone. ECOS offers various plans ranging from $49 to $4,999 for different hash rates and contract lengths. ECOS also provides free educational materials, customer support, and legal services for its clients. ECOS has a promotion that gives you 1 TH/s of free hash rate for 30 days when you sign up.
      • -
      - -

      How to Use a Cloud Mining Calculator

      - -

      A cloud mining calculator is a tool that helps you estimate your potential earnings from cloud mining. A cloud mining calculator takes into account various factors, such as:

      - -
        -
      • The hash rate speed that you rent from the cloud mining provider
      • -
      • The fee that you pay to the cloud mining provider
      • -
      • The electricity cost that the cloud mining provider charges
      • -
      • The current difficulty level of the Bitcoin network
      • -
      • The current price and block reward of Bitcoin
      • -
      • The pool or maintenance fees that the cloud mining provider deducts
      • -
      - -

      By entering these parameters into the calculator, you can get an idea of how much Bitcoin you can mine per day, week, month, or year. You can also compare different plans and providers to find the best option for your budget and goals.

      - -

      One example of a cloud mining calculator is CoinWarz, which allows you to calculate your profit from various cloud mining providers, such as IQ Mining, ECOS, StormGain, and more. You can also adjust the settings to simulate different scenarios and see how they affect your results.

      - -

      How to Avoid Scams and Frauds in Cloud Mining

      - - 7b8c122e87
      -
      -
      \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Crack ArtCAM 2015 Free Download.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Crack ArtCAM 2015 Free Download.md deleted file mode 100644 index 9308e710013d2fc5cef41425326e8760813fdd9b..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Crack ArtCAM 2015 Free Download.md +++ /dev/null @@ -1,135 +0,0 @@ - -

      Crack ArtCAM 2015 Free Download: Is It Worth It?

      -

      ArtCAM 2015 is a software that allows you to design and create stunning 2D and 3D models for CNC machining. Whether you want to make signs, jewelry, furniture, or sculptures, ArtCAM 2015 can help you turn your ideas into reality.

      -

      However, ArtCAM 2015 is not cheap. The software costs around $2000 for a perpetual license, which is quite expensive for many hobbyists and small businesses. Moreover, Autodesk, the company that owns ArtCAM, has discontinued the product in 2023 and no longer provides updates or support for it.

      -

      Crack ArtCAM 2015 Free Download


      DOWNLOAD >>> https://urlcod.com/2uIbXD



      -

      These factors may make some people want to crack ArtCAM 2015 and use it for free. Cracking software means bypassing its security features and activating it without paying for it. This can be done by downloading a cracked version of the software from a torrent site or applying a crack file to the original software.

      -

      But is cracking ArtCAM 2015 worth it? What are the risks and drawbacks of doing so? And what are the alternatives to cracking ArtCAM 2015? In this article, we will answer these questions and more.

      -

      What is ArtCAM 2015?

      -

      ArtCAM 2015 is a software that lets you design and create amazing 2D and 3D models for CNC machining. CNC stands for computer numerical control, which is a process of using computer-controlled machines to cut, carve, or engrave materials such as wood, metal, plastic, or stone.

      -

      With ArtCAM 201 5, you can create your own designs from scratch or import existing images, vectors, or 3D models. You can also use the built-in libraries of clipart, fonts, textures, and relief styles to enhance your designs. You can edit, sculpt, and transform your models using various tools and effects. You can also simulate how your models will look like after machining and generate the toolpaths for your CNC machine.

      -

      ArtCAM 2015 is a powerful and versatile software that can help you unleash your creativity and produce high-quality results. Some of the features and benefits of ArtCAM 2015 are:

      -
        -
      • It supports a wide range of file formats, such as BMP, JPG, PNG, TIFF, SVG, DXF, DWG, STL, OBJ, and more.
      • -
      • It has a user-friendly interface that is easy to learn and use.
      • -
      • It has a flexible workflow that allows you to switch between 2D and 3D modes at any time.
      • -
      • It has a fast and accurate rendering engine that shows you realistic previews of your models.
      • -
      • It has a smart nesting feature that optimizes the use of material and reduces waste.
      • -
      • It has a comprehensive help system that provides tutorials, videos, tips, and online support.
      • -
      -

      Why Do Some People Want to Crack ArtCAM 2015?

      -

      ArtCAM 2015 is undoubtedly a great software for CNC enthusiasts and professionals. However, it also has some drawbacks that may make some people want to crack it and use it for free. Some of these drawbacks are:

      -
        -
      • It is expensive. ArtCAM 2015 costs around $2000 for a perpetual license, which is a lot of money for many hobbyists and small businesses. Moreover, Autodesk does not offer any discounts or payment plans for ArtCAM 2015.
      • -
      • It is discontinued. Autodesk has discontinued ArtCAM 2015 in 2023, which means that the software will no longer receive any updates or support from the company. This also means that the software may become obsolete or incompatible with future operating systems or hardware.
      • -
      • It is hard to find. Since ArtCAM 2015 is discontinued, it is not available for purchase or download from Autodesk's website or any authorized resellers. The only way to get ArtCAM 2015 is to buy a second-hand license from someone who already owns it or to crack it from an unofficial source.
      • -
      -

      These factors may tempt some people to crack ArtCAM 2015 and use it for free. Cracking software means breaking its security features and activating it without paying for it. This can be done by downloading a cracked version of the software from a torrent site or applying a crack file to the original software.

      -

      How to Crack ArtCAM 2015?

      -

      If you are one of those people who want to crack ArtCAM 2015 and use it for free, you may be wondering how to do it. There are many websites and videos that claim to offer cracked versions of ArtCAM 2015 or crack files for ArtCAM 2015. However, not all of them are reliable or safe. Some of them may contain viruses, malware, spyware, or ransomware that can harm your computer or steal your data. Some of them may also be fake or outdated and not work properly.

      -

      -

      Therefore, you need to be careful and cautious when cracking ArtCAM 2015. You need to find a trustworthy source that provides a working and clean version of ArtCAM 2015 or a crack file for ArtCAM 2015. You also need to follow the instructions carefully and backup your data before cracking ArtCAM 2015.

      -

      To help you crack ArtCAM 2015 safely and successfully, we have prepared a step-by-step guide on how to do it. Here are the steps you need to follow:

      -

      Step 1: Download ArtCAM 2015 from a Torrent Site

      -

      The first step is to download ArtCAM 2015 from a torrent site. A torrent site is a website that allows users to share files using peer-to-peer (P2P) technology. You can find many torrent sites on the internet, such as 1337X or HaxPC. However, not all torrent sites are safe or legal. Some of them may contain malicious files or infringe on intellectual property rights.

      -

      Therefore, you need to choose a torrent site that is reputable and reliable. You also need to use a VPN (virtual private network) service to protect your identity and privacy when downloading files from torrent sites. A VPN service encrypts your internet traffic and hides your IP address from prying eyes.

      -

      To download ArtCAM 2015 from a torrent site, you need to follow these steps:

      -
        -
      1. Go to a torrent site that offers ArtCAM 2015, such as 1337X or HaxPC. You can use a search engine to find them or use the links below:
        -1337X: ArtCAM 2015
        -HaxPC: ArtCAM 2015
      2. -
      3. Find the torrent file that has the most seeders and leechers. Seeders are users who have the complete file and are sharing it with others. Leechers are users who are downloading the file and may or may not share it with others. The more seeders and leechers a torrent file has, the faster and more reliable the download will be.
      4. -
      5. Download the torrent file to your computer. You will need a torrent client software to open and manage the torrent file. A torrent client software is a program that connects you to other users who have the file and downloads it to your computer. Some of the popular torrent client software are uTorrent, BitTorrent, or qBittorrent. You can download them from their official websites or use the links below:
        -uTorrent
        -BitTorrent
        -qBittorrent
      6. -
      7. Open the torrent file with your torrent client software and start the download. You may need to choose a location on your computer where you want to save the downloaded files. You may also need to adjust some settings on your torrent client software, such as bandwidth limit, download speed, or encryption. You can refer to the help section of your torrent client software for more details.
      8. -
      9. Wait for the download to finish. Depending on the size of the file and the speed of your internet connection, this may take from a few minutes to a few hours. You can check the progress of the download on your torrent client software.
      10. -
      -

      Step 2: Download a Crack File for ArtCAM 2015

      -

      The next step is to download a crack file for ArtCAM 2015. A crack file is a file that modifies or replaces some parts of the original software to bypass its security features and activate it without paying for it. A crack file can be an executable file, a patch file, a keygen file, or a serial number file.

      -

      There are many websites and videos that claim to offer crack files for ArtCAM 2015. However, not all of them are reliable or safe. Some of them may contain viruses, malware, spyware, or ransomware that can harm your computer or steal your data. Some of them may also be fake or outdated and not work properly.

      -

      Therefore, you need to be careful and cautious when downloading crack files for ArtCAM 2015. You need to find a trustworthy source that provides a working and clean crack file for ArtCAM 2015. You also need to follow the instructions carefully and backup your data before applying the crack file.

      -

      To help you download a crack file for ArtCAM 2015 safely and successfully, we have prepared a step-by-step guide on how to do it. Here are the steps you need to follow:

      -
        -
      1. Go to a website that offers a crack file for ArtCAM 2015, such as Most I Want or Malware Tips. You can use a search engine to find them or use the links below:
        -Most I Want: ArtCAM 2015 Crack
        -Malware Tips: ArtCAM 2015 Crack
      2. -
      3. Find the crack file that matches your version of ArtCAM 2015 and your operating system. For example, if you have ArtCAM 2015 R2 and Windows 10, you need to find a crack file that is compatible with them.
      4. -
      5. Download the crack file to your computer. You may need to enter a password or complete a survey to access the download link. The password or survey may be provided by the website or by the uploader of the crack file.
      6. -
      7. Extract the crack file from the compressed folder using a program such as WinRAR or 7-Zip. You can download them from their official websites or use the links below:
        -WinRAR
        -7-Zip
      8. -
      9. Copy or move the crack file to the folder where you installed ArtCAM 2015 on your computer. The default location is C:\Program Files\Autodesk\ArtCAM 2015.Replace the original file with the crack file or run the crack file as an administrator. You may need to disable your antivirus or firewall software temporarily to avoid any interference.
      10. -
      -

      Step 3: Install ArtCAM 2015 on Your Computer

      -

      The third step is to install ArtCAM 2015 on your computer using the downloaded files. You need to follow the instructions provided by the torrent site or the crack file source to install ArtCAM 2015 correctly. You may also need to enter a serial number or a product key during the installation process. You can find them in the downloaded files or on the website where you downloaded them.

      -

      To install ArtCAM 2015 on your computer, you need to follow these steps:

      -
        -
      1. Double-click on the setup file of ArtCAM 2015 that you downloaded from the torrent site. The setup file may have different names, such as ArtCAM_2015_R2.exe, ArtCAM_2015_Setup.exe, or ArtCAM_2015_Installer.exe.
      2. -
      3. Follow the on-screen instructions to install ArtCAM 2015 on your computer. You may need to accept the license agreement, choose a destination folder, select a language, and enter a serial number or a product key.
      4. -
      5. Wait for the installation to finish. This may take from a few minutes to a few hours depending on your computer's speed and performance.
      6. -
      7. Restart your computer if prompted.
      8. -
      -

      Step 4: Apply the Crack File to ArtCAM 2015

      -

      The fourth step is to apply the crack file to ArtCAM 2015 using the downloaded files. You need to follow the instructions provided by the torrent site or the crack file source to apply the crack file correctly. You may also need to enter a serial number or a product key during the activation process. You can find them in the downloaded files or on the website where you downloaded them.

      -

      To apply the crack file to ArtCAM 2015, you need to follow these steps:

      -
        -
      1. Open the folder where you installed ArtCAM 2015 on your computer. The default location is C:\Program Files\Autodesk\ArtCAM 2015.
      2. -
      3. Find the original file that you replaced with the crack file or that you need to run with the crack file. The original file may have different names, such as ArtCAMPro.exe, ArtCAM.exe, or ArtCAM_2015.exe.
      4. -
      5. Right-click on the original file and select Properties. Go to the Compatibility tab and check the box that says Run this program as an administrator. Click OK.
      6. -
      7. Double-click on the original file or run it with the crack file as an administrator. You may need to enter a serial number or a product key during the activation process.
      8. -
      9. Wait for the activation to finish. This may take from a few seconds to a few minutes depending on your internet connection and security software.
      10. -
      11. Close the program and restart your computer if prompted.
      12. -
      -

      Step 5: Enjoy Using ArtCAM 2015 for Free

      -

      The final step is to enjoy using ArtCAM 2015 for free. You can now open and use ArtCAM 2015 on your computer without any limitations or restrictions. You can create and edit your own designs, import and export files, generate toolpaths, and more.

      -

      To verify that ArtCAM 2015 is working properly and enjoy using it for free, you need to follow these steps:

      -
        -
      1. Open ArtCAM 2015 on your computer by double-clicking on its icon on your desktop or in your start menu.
      2. -
      3. Check if there is any error message or warning sign that indicates that ArtCAM 2015 is not activated or not genuine. If there is none, then you have successfully cracked ArtCAM 2015.
      4. -
      5. Create a new project or open an existing one in ArtCAM 2015. Try out some of its features and functions and see if they work as expected.
      6. -
      7. Save and export your project in your preferred format and location. Check if there is any watermark or limitation that affects your output quality or size.
      8. -
      9. Congratulations! You have cracked ArtCAM 2015 and can use it for free.
      10. -
      -

      What are the Risks and Drawbacks of Cracking ArtCAM 2015?

      -

      While cracking ArtCAM 2015 may seem like an easy and convenient way to use it for free, it also comes with some risks and drawbacks that you should be aware of. Cracking software is not only illegal but also unethical and dangerous. Some of the risks and drawbacks of cracking ArtCAM 2015 are:

      -
    • Legal issues. Cracking software is a form of software piracy, which is a violation of intellectual property rights and a criminal offense in many countries. You may face legal consequences such as fines, lawsuits, or even jail time if you are caught cracking or using cracked software.
    • -
    • Malware infection. Cracking software may expose your computer to malware, which are malicious programs that can damage your system, steal your data, or hijack your online activities. Malware can come from the torrent sites, the crack files, or the cracked software itself. Malware can be hard to detect and remove and can compromise your security and privacy.
    • -
    • Data loss. Cracking software may cause data loss, which means that you may lose some or all of your files, documents, photos, videos, or other important information on your computer. Data loss can happen due to malware infection, system crash, software error, or accidental deletion. Data loss can be devastating and irreversible and can affect your personal or professional life.
    • -
    • Performance issues. Cracking software may cause performance issues, which means that your computer may run slower, freeze, crash, or malfunction more often. Performance issues can happen due to malware infection, system overload, software conflict, or compatibility issues. Performance issues can affect your productivity and efficiency and can frustrate you and your users.
    • -
    • Compatibility issues. Cracking software may cause compatibility issues, which means that your software may not work well with other programs, devices, or systems. Compatibility issues can happen due to outdated software, missing updates, unsupported features, or different versions. Compatibility issues can affect your functionality and quality and can limit your options and choices.
    • -
    • Ethical issues. Cracking software is unethical, which means that it is morally wrong and unfair to the developers and creators of the software. By cracking software, you are stealing their hard work, creativity, and innovation and depriving them of their rightful income and recognition. By cracking software, you are also disrespecting their rights, values, and efforts and harming their reputation and credibility.
    • -
    -

    As you can see, cracking ArtCAM 2015 is not worth it. It may seem like a good idea at first, but it can bring you more harm than good in the long run. You may end up losing more money, time, or data than you saved by cracking ArtCAM 2015. You may also end up facing legal troubles, security threats, or ethical dilemmas that you could have avoided by paying for ArtCAM 2015.

    -

    What are the Alternatives to Cracking ArtCAM 2015?

    -

    If you are looking for a way to use ArtCAM 2015 without cracking it or paying for it, you may be wondering if there are any alternatives to cracking ArtCAM 2015. The good news is that there are some alternatives to cracking ArtCAM 2015 that are legal, safe, and ethical. Some of these alternatives are:

    -
      -
    • Buying a perpetual license. If you have the budget and the need for ArtCAM 2015, you can buy a perpetual license from someone who already owns it and is willing to sell it to you. A perpetual license means that you can use ArtCAM 2015 forever without any expiration date or subscription fee. However, you need to make sure that the seller is legitimate and trustworthy and that the license is genuine and transferable.
    • -
    • Using a free trial version. If you want to try out ArtCAM 2015 before buying it or for a short-term project, you can use a free trial version of ArtCAM 2015 that is available online. A free trial version means that you can use ArtCAM 2015 for a limited time (usually 30 days) without paying for it. However, you need to make sure that the trial version is official and updated and that you do not violate its terms and conditions.
    • -
    • Using an open-source software. If you are looking for a similar software to ArtCAM 2015 that is free and accessible to everyone, you can use an open-source software that is available online. An open-source software means that its source code is publicly available and anyone can modify or improve it. However , you need to make sure that the open-source software is compatible and reliable and that you acknowledge its contributors and license.
    • -
    • Hiring a professional service. If you are looking for a high-quality and customized service that can create 2D and 3D models for CNC machining for you, you can hire a professional service that is available online. A professional service means that you can outsource your project to a qualified and experienced team that can deliver your desired results. However, you need to make sure that the professional service is reputable and affordable and that you communicate your requirements and expectations clearly.
    • -
    -

    As you can see, there are some alternatives to cracking ArtCAM 2015 that are legal, safe, and ethical. You can choose the one that suits your needs and preferences best. You can also compare the pros and cons of each alternative and weigh them against the risks and drawbacks of cracking ArtCAM 2015.

    -

    Conclusion

    -

    ArtCAM 2015 is a software that allows you to design and create stunning 2D and 3D models for CNC machining. It is a powerful and versatile software that can help you unleash your creativity and produce high-quality results.

    -

    However, ArtCAM 2015 is also expensive, discontinued, and hard to find. These factors may make some people want to crack ArtCAM 2015 and use it for free. Cracking software means bypassing its security features and activating it without paying for it.

    -

    But cracking ArtCAM 2015 is not worth it. It may seem like an easy and convenient way to use it for free, but it also comes with some risks and drawbacks that you should be aware of. Cracking software is illegal, unethical, and dangerous. It may expose you to legal troubles, security threats, data loss, performance issues, compatibility issues, or ethical dilemmas.

    -

    Therefore, we do not recommend cracking ArtCAM 2015 or any other software. Instead, we suggest using some of the alternatives to cracking ArtCAM 2015 that are legal, safe, and ethical. You can buy a perpetual license, use a free trial version, use an open-source software, or hire a professional service.

    -

    By doing so, you can use ArtCAM 2015 or a similar software without cracking it or paying for it. You can also avoid the risks and drawbacks of cracking ArtCAM 2015 or any other software. You can also support the developers and creators of the software and respect their rights, values, and efforts.

    -

    FAQs

    -

    Here are some frequently asked questions and answers related to cracking ArtCAM 2015:

    -
      -
    1. What is ArtCAM 2015?
      -ArtCAM 2015 is a software that allows you to design and create stunning 2D and 3D models for CNC machining.
    2. -
    3. Why do some people want to crack ArtCAM 2015?
      -Some people want to crack ArtCAM 2015 because it is expensive, discontinued, and hard to find.
    4. -
    5. How to crack ArtCAM 2015?
      -To crack ArtCAM 2015, you need to download ArtCAM 2015 from a torrent site, download a crack file for ArtCAM 2015 from a website, install ArtCAM 2015 on your computer, apply the crack file to ArtCAM 2015, and enjoy using ArtCAM 2015 for free.
    6. -
    7. What are the risks and drawbacks of cracking ArtCAM 2015?
      -The risks and drawbacks of cracking ArtCAM 2015 are legal issues, malware infection, data loss, performance issues, compatibility issues, and ethical issues.
    8. -
    9. What are the alternatives to cracking ArtCAM 2015?
      -The alternatives to cracking ArtCAM 2015 are buying a perpetual license, using a free trial version, using an open-source software, or hiring a professional service.
    10. -

    b2dd77e56b
    -
    -
    \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Download Nirvana Unplugged Full Album Rar.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Download Nirvana Unplugged Full Album Rar.md deleted file mode 100644 index 6f6d1dbb4a6df2bba51cf3cbfc16a07f6cb7e78a..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Download Nirvana Unplugged Full Album Rar.md +++ /dev/null @@ -1,23 +0,0 @@ -
    -

    How to Download Nirvana Unplugged Full Album Rar

    -

    If you are a fan of Nirvana, you might be interested in downloading their MTV Unplugged performance, which is widely regarded as one of the best live albums of all time. The album features acoustic versions of some of their most popular songs, as well as covers of artists like David Bowie, The Meat Puppets, and Lead Belly. In this article, we will show you how to download Nirvana Unplugged full album rar file for free.

    -

    What is a RAR file?

    -

    A RAR file is a compressed archive that can contain multiple files and folders. It is similar to a ZIP file, but it uses a more advanced compression algorithm that can reduce the file size more effectively. RAR files are often used to share large files over the internet, such as music albums, movies, or games.

    -

    Download Nirvana Unplugged Full Album Rar


    Download === https://urlcod.com/2uIaY2



    -

    How to download Nirvana Unplugged full album rar file?

    -

    There are many websites that offer Nirvana Unplugged full album rar file for download, but not all of them are safe or legal. Some of them may contain viruses, malware, or spyware that can harm your computer or steal your personal information. Some of them may also violate the copyright laws and infringe on the rights of the artists and record labels.

    -

    To avoid these risks, we recommend you to use a reputable and trustworthy website that provides legal and safe downloads of Nirvana Unplugged full album rar file. One such website is Archive.org, which is a non-profit digital library that hosts millions of free books, movies, music, and other media. Archive.org has a collection of Nirvana's live performances, including their MTV Unplugged in New York album[^1^]. You can download the album as a rar file from this link: https://archive.org/download/NIRVANA-MTVunplugged/NIRVANA-MTVunplugged.rar.

    -

    How to open Nirvana Unplugged full album rar file?

    -

    After downloading the rar file, you will need a software that can extract the files and folders inside it. One of the most popular and widely used software for this purpose is WinRAR, which is available for Windows, Mac, and Linux operating systems. You can download WinRAR from this link: https://www.win-rar.com/download.html.

    -

    Once you have installed WinRAR, you can follow these steps to open Nirvana Unplugged full album rar file:

    -
      -
    1. Locate the rar file on your computer and right-click on it.
    2. -
    3. Select "Extract Here" from the menu that appears.
    4. -
    5. Wait for WinRAR to extract the files and folders inside the rar file.
    6. -
    7. You will see a folder named "NIRVANA-MTVunplugged" that contains 14 mp3 files of the songs from the album.
    8. -
    9. You can now play the songs using your preferred media player or transfer them to your mobile device.
    10. -
    -

    Conclusion

    -

    Nirvana Unplugged is a legendary live album that showcases the talent and charisma of Kurt Cobain and his bandmates. If you want to download Nirvana Unplugged full album rar file for free, you can use Archive.org as a reliable and legal source. You will also need WinRAR to extract the files and folders inside the rar file. We hope this article was helpful and informative for you. Enjoy listening to Nirvana Unplugged!

    7b8c122e87
    -
    -
    \ No newline at end of file diff --git a/spaces/nikitaPDL2023/assignment4/detectron2/detectron2/modeling/meta_arch/panoptic_fpn.py b/spaces/nikitaPDL2023/assignment4/detectron2/detectron2/modeling/meta_arch/panoptic_fpn.py deleted file mode 100644 index b31e1c8dc06913d413ae829426e0625fdd5c2f38..0000000000000000000000000000000000000000 --- a/spaces/nikitaPDL2023/assignment4/detectron2/detectron2/modeling/meta_arch/panoptic_fpn.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. - -import logging -from typing import Dict, List -import torch -from torch import nn - -from detectron2.config import configurable -from detectron2.structures import ImageList - -from ..postprocessing import detector_postprocess, sem_seg_postprocess -from .build import META_ARCH_REGISTRY -from .rcnn import GeneralizedRCNN -from .semantic_seg import build_sem_seg_head - -__all__ = ["PanopticFPN"] - - -@META_ARCH_REGISTRY.register() -class PanopticFPN(GeneralizedRCNN): - """ - Implement the paper :paper:`PanopticFPN`. - """ - - @configurable - def __init__( - self, - *, - sem_seg_head: nn.Module, - combine_overlap_thresh: float = 0.5, - combine_stuff_area_thresh: float = 4096, - combine_instances_score_thresh: float = 0.5, - **kwargs, - ): - """ - NOTE: this interface is experimental. - - Args: - sem_seg_head: a module for the semantic segmentation head. - combine_overlap_thresh: combine masks into one instances if - they have enough overlap - combine_stuff_area_thresh: ignore stuff areas smaller than this threshold - combine_instances_score_thresh: ignore instances whose score is - smaller than this threshold - - Other arguments are the same as :class:`GeneralizedRCNN`. - """ - super().__init__(**kwargs) - self.sem_seg_head = sem_seg_head - # options when combining instance & semantic outputs - self.combine_overlap_thresh = combine_overlap_thresh - self.combine_stuff_area_thresh = combine_stuff_area_thresh - self.combine_instances_score_thresh = combine_instances_score_thresh - - @classmethod - def from_config(cls, cfg): - ret = super().from_config(cfg) - ret.update( - { - "combine_overlap_thresh": cfg.MODEL.PANOPTIC_FPN.COMBINE.OVERLAP_THRESH, - "combine_stuff_area_thresh": cfg.MODEL.PANOPTIC_FPN.COMBINE.STUFF_AREA_LIMIT, - "combine_instances_score_thresh": cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH, # noqa - } - ) - ret["sem_seg_head"] = build_sem_seg_head(cfg, ret["backbone"].output_shape()) - logger = logging.getLogger(__name__) - if not cfg.MODEL.PANOPTIC_FPN.COMBINE.ENABLED: - logger.warning( - "PANOPTIC_FPN.COMBINED.ENABLED is no longer used. " - " model.inference(do_postprocess=) should be used to toggle postprocessing." - ) - if cfg.MODEL.PANOPTIC_FPN.INSTANCE_LOSS_WEIGHT != 1.0: - w = cfg.MODEL.PANOPTIC_FPN.INSTANCE_LOSS_WEIGHT - logger.warning( - "PANOPTIC_FPN.INSTANCE_LOSS_WEIGHT should be replaced by weights on each ROI head." - ) - - def update_weight(x): - if isinstance(x, dict): - return {k: v * w for k, v in x.items()} - else: - return x * w - - roi_heads = ret["roi_heads"] - roi_heads.box_predictor.loss_weight = update_weight(roi_heads.box_predictor.loss_weight) - roi_heads.mask_head.loss_weight = update_weight(roi_heads.mask_head.loss_weight) - return ret - - def forward(self, batched_inputs): - """ - 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 - * "sem_seg": semantic segmentation ground truth. - * 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: - list[dict]: - each dict has the results for one image. The dict contains the following keys: - - * "instances": see :meth:`GeneralizedRCNN.forward` for its format. - * "sem_seg": see :meth:`SemanticSegmentor.forward` for its format. - * "panoptic_seg": See the return value of - :func:`combine_semantic_and_instance_outputs` for its format. - """ - if not self.training: - return self.inference(batched_inputs) - images = self.preprocess_image(batched_inputs) - features = self.backbone(images.tensor) - - assert "sem_seg" in batched_inputs[0] - gt_sem_seg = [x["sem_seg"].to(self.device) for x in batched_inputs] - gt_sem_seg = ImageList.from_tensors( - gt_sem_seg, - self.backbone.size_divisibility, - self.sem_seg_head.ignore_value, - self.backbone.padding_constraints, - ).tensor - sem_seg_results, sem_seg_losses = self.sem_seg_head(features, gt_sem_seg) - - gt_instances = [x["instances"].to(self.device) for x in batched_inputs] - proposals, proposal_losses = self.proposal_generator(images, features, gt_instances) - detector_results, detector_losses = self.roi_heads( - images, features, proposals, gt_instances - ) - - losses = sem_seg_losses - losses.update(proposal_losses) - losses.update(detector_losses) - return losses - - def inference(self, batched_inputs: List[Dict[str, torch.Tensor]], do_postprocess: bool = True): - """ - Run inference on the given inputs. - - Args: - batched_inputs (list[dict]): same as in :meth:`forward` - do_postprocess (bool): whether to apply post-processing on the outputs. - - Returns: - When do_postprocess=True, see docs in :meth:`forward`. - Otherwise, returns a (list[Instances], list[Tensor]) that contains - the raw detector outputs, and raw semantic segmentation outputs. - """ - images = self.preprocess_image(batched_inputs) - features = self.backbone(images.tensor) - sem_seg_results, sem_seg_losses = self.sem_seg_head(features, None) - proposals, _ = self.proposal_generator(images, features, None) - detector_results, _ = self.roi_heads(images, features, proposals, None) - - if do_postprocess: - processed_results = [] - for sem_seg_result, detector_result, input_per_image, image_size in zip( - sem_seg_results, detector_results, batched_inputs, images.image_sizes - ): - height = input_per_image.get("height", image_size[0]) - width = input_per_image.get("width", image_size[1]) - sem_seg_r = sem_seg_postprocess(sem_seg_result, image_size, height, width) - detector_r = detector_postprocess(detector_result, height, width) - - processed_results.append({"sem_seg": sem_seg_r, "instances": detector_r}) - - panoptic_r = combine_semantic_and_instance_outputs( - detector_r, - sem_seg_r.argmax(dim=0), - self.combine_overlap_thresh, - self.combine_stuff_area_thresh, - self.combine_instances_score_thresh, - ) - processed_results[-1]["panoptic_seg"] = panoptic_r - return processed_results - else: - return detector_results, sem_seg_results - - -def combine_semantic_and_instance_outputs( - instance_results, - semantic_results, - overlap_threshold, - stuff_area_thresh, - instances_score_thresh, -): - """ - Implement a simple combining logic following - "combine_semantic_and_instance_predictions.py" in panopticapi - to produce panoptic segmentation outputs. - - Args: - instance_results: output of :func:`detector_postprocess`. - semantic_results: an (H, W) tensor, each element is the contiguous semantic - category id - - Returns: - panoptic_seg (Tensor): of shape (height, width) where the values are ids for each segment. - segments_info (list[dict]): Describe each segment in `panoptic_seg`. - Each dict contains keys "id", "category_id", "isthing". - """ - panoptic_seg = torch.zeros_like(semantic_results, dtype=torch.int32) - - # sort instance outputs by scores - sorted_inds = torch.argsort(-instance_results.scores) - - current_segment_id = 0 - segments_info = [] - - instance_masks = instance_results.pred_masks.to(dtype=torch.bool, device=panoptic_seg.device) - - # Add instances one-by-one, check for overlaps with existing ones - for inst_id in sorted_inds: - score = instance_results.scores[inst_id].item() - if score < instances_score_thresh: - break - mask = instance_masks[inst_id] # H,W - mask_area = mask.sum().item() - - if mask_area == 0: - continue - - intersect = (mask > 0) & (panoptic_seg > 0) - intersect_area = intersect.sum().item() - - if intersect_area * 1.0 / mask_area > overlap_threshold: - continue - - if intersect_area > 0: - mask = mask & (panoptic_seg == 0) - - current_segment_id += 1 - panoptic_seg[mask] = current_segment_id - segments_info.append( - { - "id": current_segment_id, - "isthing": True, - "score": score, - "category_id": instance_results.pred_classes[inst_id].item(), - "instance_id": inst_id.item(), - } - ) - - # Add semantic results to remaining empty areas - semantic_labels = torch.unique(semantic_results).cpu().tolist() - for semantic_label in semantic_labels: - if semantic_label == 0: # 0 is a special "thing" class - continue - mask = (semantic_results == semantic_label) & (panoptic_seg == 0) - mask_area = mask.sum().item() - if mask_area < stuff_area_thresh: - continue - - current_segment_id += 1 - panoptic_seg[mask] = current_segment_id - segments_info.append( - { - "id": current_segment_id, - "isthing": False, - "category_id": semantic_label, - "area": mask_area, - } - ) - - return panoptic_seg, segments_info diff --git a/spaces/noelshin/selfmask/networks/timm_vit.py b/spaces/noelshin/selfmask/networks/timm_vit.py deleted file mode 100644 index fe8aea2eb1fc17066c0d9b1a6541461dff12a46b..0000000000000000000000000000000000000000 --- a/spaces/noelshin/selfmask/networks/timm_vit.py +++ /dev/null @@ -1,819 +0,0 @@ -""" Vision Transformer (ViT) in PyTorch - -A PyTorch implement of Vision Transformers as described in -'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 - -The official jax code is released and available at https://github.com/google-research/vision_transformer - -DeiT model defs and weights from https://github.com/facebookresearch/deit, -paper `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 - -Acknowledgments: -* The paper authors for releasing code and weights, thanks! -* I fixed my class token impl based on Phil Wang's https://github.com/lucidrains/vit-pytorch ... check it out -for some einops/einsum fun -* Simple transformer style inspired by Andrej Karpathy's https://github.com/karpathy/minGPT -* Bert reference code checks against Huggingface Transformers and Tensorflow Bert - -Hacked together by / Copyright 2020 Ross Wightman -""" -import math -import logging -from functools import partial -from collections import OrderedDict -from copy import deepcopy - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD -from timm.models.helpers import build_model_with_cfg, overlay_external_default_cfg -from timm.models.layers import PatchEmbed, Mlp, DropPath, trunc_normal_, lecun_normal_ -from timm.models.registry import register_model - -_logger = logging.getLogger(__name__) - - -def _cfg(url='', **kwargs): - return { - 'url': url, - 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, - 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, - 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, - 'first_conv': 'patch_embed.proj', 'classifier': 'head', - **kwargs - } - - -default_cfgs = { - # patch models (my experiments) - 'vit_small_patch16_224': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/vit_small_p16_224-15ec54c9.pth', - ), - - # patch models (weights ported from official Google JAX impl) - 'vit_base_patch16_224': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_224-80ecf9dd.pth', - mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), - ), - 'vit_base_patch32_224': _cfg( - url='', # no official model weights for this combo, only for in21k - mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_base_patch16_384': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p16_384-83fb41ba.pth', - input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), - 'vit_base_patch32_384': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_p32_384-830016f5.pth', - input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), - 'vit_large_patch16_224': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_224-4ee7a4dc.pth', - mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_large_patch32_224': _cfg( - url='', # no official model weights for this combo, only for in21k - mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_large_patch16_384': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p16_384-b3be5167.pth', - input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), - 'vit_large_patch32_384': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth', - input_size=(3, 384, 384), mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), crop_pct=1.0), - - # patch models, imagenet21k (weights ported from official Google JAX impl) - 'vit_base_patch16_224_in21k': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_patch16_224_in21k-e5005f0a.pth', - num_classes=21843, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_base_patch32_224_in21k': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_base_patch32_224_in21k-8db57226.pth', - num_classes=21843, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_large_patch16_224_in21k': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch16_224_in21k-606da67d.pth', - num_classes=21843, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_large_patch32_224_in21k': _cfg( - url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch32_224_in21k-9046d2e7.pth', - num_classes=21843, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - 'vit_huge_patch14_224_in21k': _cfg( - hf_hub='timm/vit_huge_patch14_224_in21k', - num_classes=21843, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), - - # deit models (FB weights) - 'vit_deit_tiny_patch16_224': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_tiny_patch16_224-a1311bcf.pth'), - 'vit_deit_small_patch16_224': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_small_patch16_224-cd65a155.pth'), - 'vit_deit_base_patch16_224': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth',), - 'vit_deit_base_patch16_384': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_384-8de9b5d1.pth', - input_size=(3, 384, 384), crop_pct=1.0), - 'vit_deit_tiny_distilled_patch16_224': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth', - classifier=('head', 'head_dist')), - 'vit_deit_small_distilled_patch16_224': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth', - classifier=('head', 'head_dist')), - 'vit_deit_base_distilled_patch16_224': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_224-df68dfff.pth', - classifier=('head', 'head_dist')), - 'vit_deit_base_distilled_patch16_384': _cfg( - url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_384-d0272ac0.pth', - input_size=(3, 384, 384), crop_pct=1.0, classifier=('head', 'head_dist')), - - # ViT ImageNet-21K-P pretraining - 'vit_base_patch16_224_miil_in21k': _cfg( - url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm/vit_base_patch16_224_in21k_miil.pth', - mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', num_classes=11221, - ), - 'vit_base_patch16_224_miil': _cfg( - url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm' - '/vit_base_patch16_224_1k_miil_84_4.pth', - mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', - ), -} - - -class Attention(nn.Module): - def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): - super().__init__() - self.num_heads = num_heads - head_dim = dim // num_heads - self.scale = qk_scale or head_dim ** -0.5 - - self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) - self.attn_drop = nn.Dropout(attn_drop) - self.proj = nn.Linear(dim, dim) - self.proj_drop = nn.Dropout(proj_drop) - - def forward(self, x): - B, N, C = x.shape - qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) - - attn = (q @ k.transpose(-2, -1)) * self.scale - attn = attn.softmax(dim=-1) - attn = self.attn_drop(attn) - - x = (attn @ v).transpose(1, 2).reshape(B, N, C) - x = self.proj(x) - x = self.proj_drop(x) - return x - - -class Block(nn.Module): - - def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., - drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): - super().__init__() - self.norm1 = norm_layer(dim) - self.attn = Attention( - dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) - # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here - self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() - self.norm2 = norm_layer(dim) - mlp_hidden_dim = int(dim * mlp_ratio) - self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) - - def forward(self, x): - x = x + self.drop_path(self.attn(self.norm1(x))) - x = x + self.drop_path(self.mlp(self.norm2(x))) - return x - - -class VisionTransformer(nn.Module): - """ Vision Transformer - - A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - - https://arxiv.org/abs/2010.11929 - - Includes distillation token & head support for `DeiT: Data-efficient Image Transformers` - - https://arxiv.org/abs/2012.12877 - """ - - def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, - num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None, distilled=False, - drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None, - act_layer=None, weight_init='', - # noel - img_size_eval: int = 224): - """ - Args: - img_size (int, tuple): input image size - patch_size (int, tuple): patch size - in_chans (int): number of input channels - num_classes (int): number of classes for classification head - embed_dim (int): embedding dimension - depth (int): depth of transformer - num_heads (int): number of attention heads - mlp_ratio (int): ratio of mlp hidden dim to embedding dim - qkv_bias (bool): enable bias for qkv if True - qk_scale (float): override default qk scale of head_dim ** -0.5 if set - representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set - distilled (bool): model includes a distillation token and head as in DeiT models - drop_rate (float): dropout rate - attn_drop_rate (float): attention dropout rate - drop_path_rate (float): stochastic depth rate - embed_layer (nn.Module): patch embedding layer - norm_layer: (nn.Module): normalization layer - weight_init: (str): weight init scheme - """ - super().__init__() - self.num_classes = num_classes - self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models - self.num_tokens = 2 if distilled else 1 - norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) - act_layer = act_layer or nn.GELU - - self.patch_embed = embed_layer( - img_size=img_size, - patch_size=patch_size, - in_chans=in_chans, - embed_dim=embed_dim - ) - num_patches = self.patch_embed.num_patches - - self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) - self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None - self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) - self.pos_drop = nn.Dropout(p=drop_rate) - - dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule - self.blocks = nn.Sequential(*[ - Block( - dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, - drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer) - for i in range(depth)]) - self.norm = norm_layer(embed_dim) - - # Representation layer - if representation_size and not distilled: - self.num_features = representation_size - self.pre_logits = nn.Sequential(OrderedDict([ - ('fc', nn.Linear(embed_dim, representation_size)), - ('act', nn.Tanh()) - ])) - else: - self.pre_logits = nn.Identity() - - # Classifier head(s) - self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() - self.head_dist = None - if distilled: - self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() - - # Weight init - assert weight_init in ('jax', 'jax_nlhb', 'nlhb', '') - head_bias = -math.log(self.num_classes) if 'nlhb' in weight_init else 0. - trunc_normal_(self.pos_embed, std=.02) - if self.dist_token is not None: - trunc_normal_(self.dist_token, std=.02) - if weight_init.startswith('jax'): - # leave cls token as zeros to match jax impl - for n, m in self.named_modules(): - _init_vit_weights(m, n, head_bias=head_bias, jax_impl=True) - else: - trunc_normal_(self.cls_token, std=.02) - self.apply(_init_vit_weights) - - # noel - self.depth = depth - self.distilled = distilled - self.patch_size = patch_size - self.patch_embed.img_size = (img_size_eval, img_size_eval) - - def _init_weights(self, m): - # this fn left here for compat with downstream users - _init_vit_weights(m) - - @torch.jit.ignore - def no_weight_decay(self): - return {'pos_embed', 'cls_token', 'dist_token'} - - def get_classifier(self): - if self.dist_token is None: - return self.head - else: - return self.head, self.head_dist - - def reset_classifier(self, num_classes, global_pool=''): - self.num_classes = num_classes - self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() - if self.num_tokens == 2: - self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() - - def forward_features(self, x): - x = self.patch_embed(x) - cls_token = self.cls_token.expand(x.shape[0], -1, -1) # stole cls_tokens impl from Phil Wang, thanks - if self.dist_token is None: - x = torch.cat((cls_token, x), dim=1) - else: - x = torch.cat((cls_token, self.dist_token.expand(x.shape[0], -1, -1), x), dim=1) - x = self.pos_drop(x + self.pos_embed) - x = self.blocks(x) - x = self.norm(x) - if self.dist_token is None: - return self.pre_logits(x[:, 0]) - else: - return x[:, 0], x[:, 1] - - # def forward(self, x): - # x = self.forward_features(x) - # if self.head_dist is not None: - # x, x_dist = self.head(x[0]), self.head_dist(x[1]) # x must be a tuple - # if self.training and not torch.jit.is_scripting(): - # # during inference, return the average of both classifier predictions - # return x, x_dist - # else: - # return (x + x_dist) / 2 - # else: - # x = self.head(x) - # return x - - # noel - start - def make_square(self, x: torch.Tensor): - """Pad some pixels to make the input size divisible by the patch size.""" - B, _, H_0, W_0 = x.shape - pad_w = (self.patch_size - W_0 % self.patch_size) % self.patch_size - pad_h = (self.patch_size - H_0 % self.patch_size) % self.patch_size - x = nn.functional.pad(x, (0, pad_w, 0, pad_h), value=x.mean()) - - H_p, W_p = H_0 + pad_h, W_0 + pad_w - x = nn.functional.pad(x, (0, H_p - W_p, 0, 0) if H_p > W_p else (0, 0, 0, W_p - H_p), value=x.mean()) - return x - - def interpolate_pos_encoding(self, x, pos_embed, size): - """Interpolate the learnable positional encoding to match the number of patches. - - x: B x (1 + N patches) x dim_embedding - pos_embed: B x (1 + N patches) x dim_embedding - - return interpolated positional embedding - """ - npatch = x.shape[1] - 1 # (H // patch_size * W // patch_size) - N = pos_embed.shape[1] - 1 # 784 (= 28 x 28) - if npatch == N: - return pos_embed - class_emb, pos_embed = pos_embed[:, 0], pos_embed[:, 1:] # a learnable CLS token, learnable position embeddings - - dim = x.shape[-1] # dimension of embeddings - pos_embed = nn.functional.interpolate( - pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), # B x dim x 28 x 28 - size=size, - mode='bicubic', - align_corners=False - ) - - pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) - pos_embed = torch.cat((class_emb.unsqueeze(0), pos_embed), dim=1) - return pos_embed - - # def interpolate_pos_encoding(self, x, pos_embed): - # """Interpolate the learnable positional encoding to match the number of patches. - # - # x: B x (1 + N patches) x dim_embedding - # pos_embed: B x (1 + N patches) x dim_embedding - # - # return interpolated positional embedding - # """ - # npatch = x.shape[1] - 1 # (H // patch_size * W // patch_size) - # N = pos_embed.shape[1] - 1 # 784 (= 28 x 28) - # if npatch == N: - # return pos_embed - # class_emb, pos_embed = pos_embed[:, 0], pos_embed[:, 1:] # a learnable CLS token, learnable position embeddings - # - # dim = x.shape[-1] # dimension of embeddings - # pos_embed = nn.functional.interpolate( - # pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), # B x dim x 28 x 28 - # scale_factor=math.sqrt(npatch / N) + 1e-5, # noel: this can be a float, but the output shape will be integer. - # recompute_scale_factor=True, - # mode='bicubic', - # align_corners=False - # ) - # - # pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) - # pos_embed = torch.cat((class_emb.unsqueeze(0), pos_embed), dim=1) - # return pos_embed - - def prepare_tokens(self, x): - B, nc, h, w = x.shape - patch_embed_h, patch_embed_w = x.shape[-2] // self.patch_size, x.shape[-1] // self.patch_size - x = self.patch_embed(x) # patch linear embedding - - # add the [CLS] token to the embed patch tokens - cls_tokens = self.cls_token.expand(B, -1, -1) - x = torch.cat((cls_tokens, x), dim=1) - - # add positional encoding to each token - x = x + self.interpolate_pos_encoding(x, self.pos_embed, size=(patch_embed_h, patch_embed_w)) - return self.pos_drop(x) - - def get_tokens( - self, - x, - layers: list, - patch_tokens: bool = False, - norm: bool = True, - input_tokens: bool = False, - post_pe: bool = False - ): - """Return intermediate tokens.""" - list_tokens: list = [] - - B = x.shape[0] - x = self.patch_embed(x) - - cls_tokens = self.cls_token.expand(B, -1, -1) - - x = torch.cat((cls_tokens, x), dim=1) - - if input_tokens: - list_tokens.append(x) - - pos_embed = self.interpolate_pos_encoding(x, self.pos_embed) - x = x + pos_embed - - if post_pe: - list_tokens.append(x) - - x = self.pos_drop(x) - - for i, blk in enumerate(self.blocks): - x = blk(x) # B x # patches x dim - if layers is None or i in layers: - list_tokens.append(self.norm(x) if norm else x) - - tokens = torch.stack(list_tokens, dim=1) # B x n_layers x (1 + # patches) x dim - - if not patch_tokens: - return tokens[:, :, 0, :] # index [CLS] tokens only, B x n_layers x dim - - else: - return tokens - - def forward(self, x, layer: str = None): - x = self.prepare_tokens(x) - - features: dict = {} - for i, blk in enumerate(self.blocks): - x = blk(x) - features[f"layer{i + 1}"] = self.norm(x) - - if layer is not None: - return features[layer] - else: - return features["layer12"] - # noel - end - - -def _init_vit_weights(m, n: str = '', head_bias: float = 0., jax_impl: bool = False): - """ ViT weight initialization - * When called without n, head_bias, jax_impl args it will behave exactly the same - as my original init for compatibility with prev hparam / downstream use cases (ie DeiT). - * When called w/ valid n (module name) and jax_impl=True, will (hopefully) match JAX impl - """ - if isinstance(m, nn.Linear): - if n.startswith('head'): - nn.init.zeros_(m.weight) - nn.init.constant_(m.bias, head_bias) - elif n.startswith('pre_logits'): - lecun_normal_(m.weight) - nn.init.zeros_(m.bias) - else: - if jax_impl: - nn.init.xavier_uniform_(m.weight) - if m.bias is not None: - if 'mlp' in n: - nn.init.normal_(m.bias, std=1e-6) - else: - nn.init.zeros_(m.bias) - else: - trunc_normal_(m.weight, std=.02) - if m.bias is not None: - nn.init.zeros_(m.bias) - elif jax_impl and isinstance(m, nn.Conv2d): - # NOTE conv was left to pytorch default in my original init - lecun_normal_(m.weight) - if m.bias is not None: - nn.init.zeros_(m.bias) - elif isinstance(m, nn.LayerNorm): - nn.init.zeros_(m.bias) - nn.init.ones_(m.weight) - - -def resize_pos_embed(posemb, posemb_new, num_tokens=1, gs_new=()): - # Rescale the grid of position embeddings when loading from state_dict. Adapted from - # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 - _logger.info('Resized position embedding: %s to %s', posemb.shape, posemb_new.shape) - ntok_new = posemb_new.shape[1] - if num_tokens: - posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:] - ntok_new -= num_tokens - else: - posemb_tok, posemb_grid = posemb[:, :0], posemb[0] - gs_old = int(math.sqrt(len(posemb_grid))) - if not len(gs_new): # backwards compatibility - gs_new = [int(math.sqrt(ntok_new))] * 2 - assert len(gs_new) >= 2 - _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new) - posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) - posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode='bilinear') - posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_new[0] * gs_new[1], -1) - posemb = torch.cat([posemb_tok, posemb_grid], dim=1) - return posemb - - -def checkpoint_filter_fn(state_dict, model): - """ convert patch embedding weight from manual patchify + linear proj to conv""" - out_dict = {} - if 'model' in state_dict: - # For deit models - state_dict = state_dict['model'] - for k, v in state_dict.items(): - if 'patch_embed.proj.weight' in k and len(v.shape) < 4: - # For old models that I trained prior to conv based patchification - O, I, H, W = model.patch_embed.proj.weight.shape - v = v.reshape(O, -1, H, W) - elif k == 'pos_embed' and v.shape != model.pos_embed.shape: - # To resize pos embedding when using model at different size from pretrained weights - v = resize_pos_embed( - v, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) - out_dict[k] = v - return out_dict - - -def _create_vision_transformer(variant, pretrained=False, default_cfg=None, **kwargs): - default_cfg = default_cfg or default_cfgs[variant] - if kwargs.get('features_only', None): - raise RuntimeError('features_only not implemented for Vision Transformer models.') - - # NOTE this extra code to support handling of repr size for in21k pretrained models - default_num_classes = default_cfg['num_classes'] - num_classes = kwargs.get('num_classes', default_num_classes) - repr_size = kwargs.pop('representation_size', None) - if repr_size is not None and num_classes != default_num_classes: - # Remove representation layer if fine-tuning. This may not always be the desired action, - # but I feel better than doing nothing by default for fine-tuning. Perhaps a better interface? - _logger.warning("Removing representation layer for fine-tuning.") - repr_size = None - - model = build_model_with_cfg( - VisionTransformer, variant, pretrained, - default_cfg=default_cfg, - representation_size=repr_size, - pretrained_filter_fn=checkpoint_filter_fn, - **kwargs) - return model - - -@register_model -def vit_small_patch16_224(pretrained=False, **kwargs): - """ My custom 'small' ViT model. embed_dim=768, depth=8, num_heads=8, mlp_ratio=3. - NOTE: - * this differs from the DeiT based 'small' definitions with embed_dim=384, depth=12, num_heads=6 - * this model does not have a bias for QKV (unlike the official ViT and DeiT models) - """ - model_kwargs = dict( - patch_size=16, embed_dim=768, depth=8, num_heads=8, mlp_ratio=3., - qkv_bias=False, norm_layer=nn.LayerNorm, **kwargs) - if pretrained: - # NOTE my scale was wrong for original weights, leaving this here until I have better ones for this model - model_kwargs.setdefault('qk_scale', 768 ** -0.5) - model = _create_vision_transformer('vit_small_patch16_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch16_224(pretrained=False, **kwargs): - """ ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer('vit_base_patch16_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch32_224(pretrained=False, **kwargs): - """ ViT-Base (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929). No pretrained weights. - """ - model_kwargs = dict(patch_size=32, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer('vit_base_patch32_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch16_384(pretrained=False, **kwargs): - """ ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer('vit_base_patch16_384', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch32_384(pretrained=False, **kwargs): - """ ViT-Base model (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict(patch_size=32, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer('vit_base_patch32_384', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_large_patch16_224(pretrained=False, **kwargs): - """ ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict(patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs) - model = _create_vision_transformer('vit_large_patch16_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_large_patch32_224(pretrained=False, **kwargs): - """ ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929). No pretrained weights. - """ - model_kwargs = dict(patch_size=32, embed_dim=1024, depth=24, num_heads=16, **kwargs) - model = _create_vision_transformer('vit_large_patch32_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_large_patch16_384(pretrained=False, **kwargs): - """ ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict(patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs) - model = _create_vision_transformer('vit_large_patch16_384', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_large_patch32_384(pretrained=False, **kwargs): - """ ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-1k weights fine-tuned from in21k @ 384x384, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict(patch_size=32, embed_dim=1024, depth=24, num_heads=16, **kwargs) - model = _create_vision_transformer('vit_large_patch32_384', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch16_224_in21k(pretrained=False, **kwargs): - """ ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict( - patch_size=16, embed_dim=768, depth=12, num_heads=12, representation_size=768, **kwargs) - model = _create_vision_transformer('vit_base_patch16_224_in21k', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch32_224_in21k(pretrained=False, **kwargs): - """ ViT-Base model (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict( - patch_size=32, embed_dim=768, depth=12, num_heads=12, representation_size=768, **kwargs) - model = _create_vision_transformer('vit_base_patch32_224_in21k', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_large_patch16_224_in21k(pretrained=False, **kwargs): - """ ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict( - patch_size=16, embed_dim=1024, depth=24, num_heads=16, representation_size=1024, **kwargs) - model = _create_vision_transformer('vit_large_patch16_224_in21k', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_large_patch32_224_in21k(pretrained=False, **kwargs): - """ ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. - """ - model_kwargs = dict( - patch_size=32, embed_dim=1024, depth=24, num_heads=16, representation_size=1024, **kwargs) - model = _create_vision_transformer('vit_large_patch32_224_in21k', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_huge_patch14_224_in21k(pretrained=False, **kwargs): - """ ViT-Huge model (ViT-H/14) from original paper (https://arxiv.org/abs/2010.11929). - ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. - NOTE: converted weights not currently available, too large for github release hosting. - """ - model_kwargs = dict( - patch_size=14, embed_dim=1280, depth=32, num_heads=16, representation_size=1280, **kwargs) - model = _create_vision_transformer('vit_huge_patch14_224_in21k', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_deit_tiny_patch16_224(pretrained=False, **kwargs): - """ DeiT-tiny model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=192, depth=12, num_heads=3, **kwargs) - model = _create_vision_transformer('vit_deit_tiny_patch16_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_deit_small_patch16_224(pretrained=False, **kwargs): - """ DeiT-small model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs) - model = _create_vision_transformer('vit_deit_small_patch16_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_deit_base_patch16_224(pretrained=False, **kwargs): - """ DeiT base model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer('vit_deit_base_patch16_224', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_deit_base_patch16_384(pretrained=False, **kwargs): - """ DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer('vit_deit_base_patch16_384', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_deit_tiny_distilled_patch16_224(pretrained=False, **kwargs): - """ DeiT-tiny distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=192, depth=12, num_heads=3, **kwargs) - model = _create_vision_transformer( - 'vit_deit_tiny_distilled_patch16_224', pretrained=pretrained, distilled=True, **model_kwargs) - return model - - -@register_model -def vit_deit_small_distilled_patch16_224(pretrained=False, **kwargs): - """ DeiT-small distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs) - model = _create_vision_transformer( - 'vit_deit_small_distilled_patch16_224', pretrained=pretrained, distilled=True, **model_kwargs) - return model - - -@register_model -def vit_deit_base_distilled_patch16_224(pretrained=False, **kwargs): - """ DeiT-base distilled model @ 224x224 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer( - 'vit_deit_base_distilled_patch16_224', pretrained=pretrained, distilled=True, **model_kwargs) - return model - - -@register_model -def vit_deit_base_distilled_patch16_384(pretrained=False, **kwargs): - """ DeiT-base distilled model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). - ImageNet-1k weights from https://github.com/facebookresearch/deit. - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) - model = _create_vision_transformer( - 'vit_deit_base_distilled_patch16_384', pretrained=pretrained, distilled=True, **model_kwargs) - return model - - -@register_model -def vit_base_patch16_224_miil_in21k(pretrained=False, **kwargs): - """ ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). - Weights taken from: https://github.com/Alibaba-MIIL/ImageNet21K - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, qkv_bias=False, **kwargs) - model = _create_vision_transformer('vit_base_patch16_224_miil_in21k', pretrained=pretrained, **model_kwargs) - return model - - -@register_model -def vit_base_patch16_224_miil(pretrained=False, **kwargs): - """ ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). - Weights taken from: https://github.com/Alibaba-MIIL/ImageNet21K - """ - model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, qkv_bias=False, **kwargs) - model = _create_vision_transformer('vit_base_patch16_224_miil', pretrained=pretrained, **model_kwargs) - return model \ No newline at end of file diff --git a/spaces/nugrahatheo/Credit_Card_Fraud_Detection/README.md b/spaces/nugrahatheo/Credit_Card_Fraud_Detection/README.md deleted file mode 100644 index ad3acdbe0a726ed48046397cf01cea597e468f7e..0000000000000000000000000000000000000000 --- a/spaces/nugrahatheo/Credit_Card_Fraud_Detection/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Credit Card Fraud Detection -emoji: 🚀 -colorFrom: pink -colorTo: pink -sdk: streamlit -sdk_version: 1.25.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/oliver2023/chatgpt-on-wechat/voice/baidu/README.md b/spaces/oliver2023/chatgpt-on-wechat/voice/baidu/README.md deleted file mode 100644 index 815bb0aefa56d0aac1299b5765e258c4a81562cf..0000000000000000000000000000000000000000 --- a/spaces/oliver2023/chatgpt-on-wechat/voice/baidu/README.md +++ /dev/null @@ -1,55 +0,0 @@ -## 说明 -百度语音识别与合成参数说明 -百度语音依赖,经常会出现问题,可能就是缺少依赖: -pip install baidu-aip -pip install pydub -pip install pysilk -还有ffmpeg,不同系统安装方式不同 - -系统中收到的语音文件为mp3格式(wx)或者sil格式(wxy),如果要识别需要转换为pcm格式,转换后的文件为16k采样率,单声道,16bit的pcm文件 -发送时又需要(wx)转换为mp3格式,转换后的文件为16k采样率,单声道,16bit的pcm文件,(wxy)转换为sil格式,还要计算声音长度,发送时需要带上声音长度 -这些事情都在audio_convert.py中封装了,直接调用即可 - - -参数说明 -识别参数 -https://ai.baidu.com/ai-doc/SPEECH/Vk38lxily -合成参数 -https://ai.baidu.com/ai-doc/SPEECH/Gk38y8lzk - -## 使用说明 -分两个地方配置 - -1、对于def voiceToText(self, filename)函数中调用的百度语音识别API,中接口调用asr(参数)这个配置见CHATGPT-ON-WECHAT工程目录下的`config.json`文件和config.py文件。 -参数 可需 描述 -app_id 必填 应用的APPID -api_key 必填 应用的APIKey -secret_key 必填 应用的SecretKey -dev_pid 必填 语言选择,填写语言对应的dev_pid值 - -2、对于def textToVoice(self, text)函数中调用的百度语音合成API,中接口调用synthesis(参数)在本目录下的`config.json`文件中进行配置。 -参数 可需 描述 -tex 必填 合成的文本,使用UTF-8编码,请注意文本长度必须小于1024字节 -lan 必填 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh -spd 选填 语速,取值0-15,默认为5中语速 -pit 选填 音调,取值0-15,默认为5中语调 -vol 选填 音量,取值0-15,默认为5中音量(取值为0时为音量最小值,并非为无声) -per(基础音库) 选填 度小宇=1,度小美=0,度逍遥(基础)=3,度丫丫=4 -per(精品音库) 选填 度逍遥(精品)=5003,度小鹿=5118,度博文=106,度小童=110,度小萌=111,度米朵=103,度小娇=5 -aue 选填 3为mp3格式(默认); 4为pcm-16k;5为pcm-8k;6为wav(内容同pcm-16k); 注意aue=4或者6是语音识别要求的格式,但是音频内容不是语音识别要求的自然人发音,所以识别效果会受影响。 - -关于per参数的说明,注意您购买的哪个音库,就填写哪个音库的参数,否则会报错。如果您购买的是基础音库,那么per参数只能填写0到4,如果您购买的是精品音库,那么per参数只能填写5003,5118,106,110,111,103,5其他的都会报错。 -### 配置文件 - -将文件夹中`config.json.template`复制为`config.json`。 - -``` json - { - "lang": "zh", - "ctp": 1, - "spd": 5, - "pit": 5, - "vol": 5, - "per": 0 - } -``` \ No newline at end of file diff --git a/spaces/omlab/VL_checklist_demo/README.md b/spaces/omlab/VL_checklist_demo/README.md deleted file mode 100644 index 7529818a0ff745599d65f5c96b394ccae526cf76..0000000000000000000000000000000000000000 --- a/spaces/omlab/VL_checklist_demo/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: VL Checklist Demo -emoji: 👀 -colorFrom: purple -colorTo: red -sdk: gradio -sdk_version: 3.1.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/omlakhani/endoai/app.py b/spaces/omlakhani/endoai/app.py deleted file mode 100644 index 74a5f6e342f5293020c6a88d5af267c71035d69d..0000000000000000000000000000000000000000 --- a/spaces/omlakhani/endoai/app.py +++ /dev/null @@ -1,211 +0,0 @@ -import gradio as gr -import os -import boto3 -from llama_index import GPTSimpleVectorIndex -from langchain.agents import ZeroShotAgent, AgentExecutor -from langchain.agents import Tool -from langchain import OpenAI, LLMChain -from cachetools import cached, TTLCache -import openai - - - -s3 = boto3.resource('s3') -bucket_name = "notesinendocrinology" -combo_index_path = "comboindex.json" -nafld_path = "nafld.json" -osteoporosis_path = "osteoporosis.json" - - -def keywords(query2): - - index1 = None - prefix_answer1 = 'According to NIE:' - suffix_answer1 = 'Lakhani OJ. EndoAI Answer [Internet]. Notes in Endocrinology. [cited 2023Mar31]. Available from: endocrinology.co.in' - - if 'NASH' in query2 or 'NAFLD' in query2 or 'Non-alcoholic fatty liver disease' in query2: - index_path = nafld_path - prefix_answer1 = "Here is the answer based on Notes in Endocrinology and American Association of Clinical Endocrinology Clinical Practice Guideline for the Diagnosis and Management of Nonalcoholic Fatty Liver Disease in Primary Care and Endocrinology Clinical Settings:" - suffix_answer1 = """Citation: \n - 1. Cusi, Kenneth, Scott Isaacs, Diana Barb, Rita Basu, Sonia Caprio, W. Timothy Garvey, Sangeeta Kashyap et al. "American Association of Clinical Endocrinology clinical practice guideline for the diagnosis and management of nonalcoholic fatty liver disease in primary care and endocrinology clinical settings: co-sponsored by the American Association for the Study of Liver Diseases (AASLD)." Endocrine Practice 28, no. 5 (2022): 528-562. - 2. Lakhani OJ. EndoAI Answer [Internet]. Notes in Endocrinology. [cited 2023Mar31]. Available from: endocrinology.co.in - """ - elif 'osteoporosis' in query2 or 'osteopenia' in query2 or 'low bone mass' in query2 or 'DEXA-BMD' in query2 or 'BMD' in query2 or 'Osteoporosis' in query2: - index_path = osteoporosis_path - prefix_answer1 = "According to : Pharmacological Management of Osteoporosis in Postmenopausal Women: An Endocrine Society* Clinical Practice Guideline & Notes in Endocrinology" - suffix_answer1 = """Citation: \n - 1. Eastell R, Rosen CJ, Black DM, Cheung AM, Murad MH, Shoback D. Pharmacological management of osteoporosis in postmenopausal women: an Endocrine Society clinical practice guideline. The Journal of Clinical Endocrinology & Metabolism. 2019 May;104(5):1595-622. - 2. Lakhani OJ. EndoAI Answer [Internet]. Notes in Endocrinology. [cited 2023Mar31]. Available from: endocrinology.co.in - """ - else: - index_path = combo_index_path - - if index1 is None: - s3.Bucket(bucket_name).download_file(index_path, index_path.split("/")[-1]) - print(f"Downloaded {index_path}") - index1 = GPTSimpleVectorIndex.load_from_disk(index_path) - - return index1, prefix_answer1, suffix_answer1 - - -def send_message(message_log): - # Use OpenAI's ChatCompletion API to get the chatbot's response - response = openai.ChatCompletion.create( - model="gpt-3.5-turbo", # The name of the OpenAI chatbot model to use - messages=message_log, # The conversation history up to this point, as a list of dictionaries - max_tokens=512, # The maximum number of tokens (words or subwords) in the generated response - stop=None, # The stopping sequence for the generated response, if any (not used here) - temperature=0.5, # The "creativity" of the generated response (higher temperature = more creative) - ) - - # Find the first response from the chatbot that has text in it (some responses may not have text) - for choice in response.choices: - if "text" in choice: - return choice.text - - # If no response with text is found, return the first response's content (which may be empty) - return response.choices[0].message.content - - -def generate_variations(question): - def extract(input): - message_log = [{"role": "system", "content": input}] - user_input = f"Generate one follow-up question from the following question: {input}. Give one more question only. The question is intended for knowledgeable doctors" - message_log.append({"role": "user", "content": user_input}) - response = send_message(message_log) - message_log.append({"role": "assistant", "content": response}) - text = str(response) - print(response) - return response - - input2 = question - - my_string = "0. " + question - output = extract(input2) - output_list = output.split("\n") - final_list = [my_string] + output_list - print(final_list) - - return final_list - - - - - -def querying_db(query: str): - get_index1 = keywords(query)[0] - response = get_index1.query(query, response_mode="default") - - return response - - -tools = [ - Tool( - name="QueryingDB", - func=querying_db, - description="useful for when you need to answer questions from the database. The answer is for knowledgeable doctors", - return_direct=True - ) -] - -prefix = "Give an answer to the question" -suffix = """Give answer intended for knowledgeable doctors - -Question: {input} -{agent_scratchpad}""" - -prompt = ZeroShotAgent.create_prompt( - tools, - prefix=prefix, - suffix=suffix, - input_variables=["input", "agent_scratchpad"] -) - -llm_chain = LLMChain(llm=OpenAI(temperature=0.5), prompt=prompt) -tool_names = [tool.name for tool in tools] -agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names) - - -def get_answer(query_string): - agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) - response = agent_executor.run(query_string) - result = f"{response}" - return result - - -def get_answer2(list_thing): - responses = [] - for question in list_thing: - answer = get_answer(question) - response = f"{question}\n{answer}" - responses.append(response) - - return "\n\n".join(responses) - - -def consolidated_answer(question, oginput): - def extract(input): - message_log = [{"role": "system", "content": input}] - user_input = f"Give a consolidated answer from this: {input}. It should answer the original question {oginput}. The answer is for knowledgeable doctors so use medical terms." - message_log.append({"role": "user", "content": user_input}) - response = send_message(message_log) - message_log.append({"role": "assistant", "content": response}) - text = str(response) - print(response) - return response - - input2 = question - - output = extract(input2) - - print(output) - return output - - -def qa_app(query1): - # 1. function that checks if relevant keyword is found in the query and get the relevant index - # 2. generate question variartions - - question_variations_list = generate_variations(query1) - prefix_answer = keywords(query1)[1] - suffix_answer = keywords(query1)[2] - # whichindex = keywords(query1)[0] - # if whichindex == 'nafld.json': - # prefix_answer = "Here is the answer based on Notes in Endocrinology and American Association of Clinical Endocrinology Clinical Practice Guideline for the Diagnosis and Management of Nonalcoholic Fatty Liver Disease in Primary Care and Endocrinology Clinical Settings:" - # suffix_answer = """Citation: \n - # - # 1. Cusi, Kenneth, Scott Isaacs, Diana Barb, Rita Basu, Sonia Caprio, W. Timothy Garvey, Sangeeta Kashyap et al. "American Association of Clinical Endocrinology clinical practice guideline for the diagnosis and management of nonalcoholic fatty liver disease in primary care and endocrinology clinical settings: co-sponsored by the American Association for the Study of Liver Diseases (AASLD)." Endocrine Practice 28, no. 5 (2022): 528-562. - # - # """ - # - # elif whichindex == 'osteoporosis_new.json': - # prefix_answer = "According to : Pharmacological Management of Osteoporosis in Postmenopausal Women: An Endocrine Society* Clinical Practice Guideline & Notes in Endocrinology" - # suffix_answer = """Citation: \n - # - # 1. Eastell R, Rosen CJ, Black DM, Cheung AM, Murad MH, Shoback D. Pharmacological management of osteoporosis in postmenopausal women: an Endocrine Society clinical practice guideline. The Journal of Clinical Endocrinology & Metabolism. 2019 May;104(5):1595-622. - # """ - # - # else: - # prefix_answer = "According to NIE:" - # suffix_answer = "Citation: NIE" - big_answer = get_answer2(question_variations_list) - final_answer = consolidated_answer(big_answer, query1) - final_answer_with_citation = prefix_answer + "\n\n" + final_answer + "\n\n" + suffix_answer - return final_answer_with_citation - - -inputs = [ - gr.inputs.Textbox(label="Enter your question:"), - -] - -output = gr.outputs.Textbox(label="Answer:") - -iface = gr.Interface( - fn=qa_app, - inputs=inputs, - outputs=output, - title="Endo AI : Endocrine answering app by Dr. Om J Lakhani" -) - -iface.launch() diff --git a/spaces/osanseviero/AnimeGANv2-webcam/app.py b/spaces/osanseviero/AnimeGANv2-webcam/app.py deleted file mode 100644 index 943ccffd79e775eb02fec43fe8316c29626e2512..0000000000000000000000000000000000000000 --- a/spaces/osanseviero/AnimeGANv2-webcam/app.py +++ /dev/null @@ -1,13 +0,0 @@ -import gradio as gr - -description = "Gradio Demo for AnimeGanv2 using your webcam! Find original repo at https://huggingface.co/spaces/akhaliq/AnimeGANv2." - -gr.Interface.load( - "spaces/akhaliq/AnimeGANv2", - inputs=[ - gr.inputs.Image(label="Input Image", source="webcam"), - gr.inputs.Radio(['version 1 (🔺 stylization, 🔻 robustness)','version 2 (🔺 robustness,🔻 stylization)'], type="value", default='version 2 (🔺 robustness,🔻 stylization)', label='version') - ], - article="", - description=description, -).launch(debug=True) \ No newline at end of file diff --git a/spaces/p-baleine/metaanalyser/README.md b/spaces/p-baleine/metaanalyser/README.md deleted file mode 100644 index 955133e787c1a4991f08256c037fdeb2516f695a..0000000000000000000000000000000000000000 --- a/spaces/p-baleine/metaanalyser/README.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Metaanalyser -emoji: 🎓 -colorFrom: blue -colorTo: gray -sdk: gradio -sdk_version: 3.28.3 -app_file: app.py -pinned: false -tags: - - LangChain - - GPT ---- - -# Metaanalyser - -This is an application that generates systematic reviews powered by GPT. It searches Google Scholar with a given query and generates a systematic review using the search results. https://huggingface.co/spaces/p-baleine/metaanalyser - -Following is a quote from Wikipedia: - -> A systematic review is a scholarly synthesis of the evidence on a clearly presented topic using critical methods to identify, define and assess research on the topic. A systematic review extracts and interprets data from published studies on the topic, then analyzes, describes, and summarizes interpretations into a refined conclusion. - -This application aims to generate a systematic review of a given topic by examining multiple literature. - -This application is an experiment. The application may exceed the maximum token length and produce errors, or produce output of such poor quality that it is not appropriate to call it a systematic review. - -## Examples - -You can find a sample output of this application in the [examples](./examples) directory (the file name is a Google Scholar search query). - -- [A Systematic Review of Large Language Model Agent and Tool Integration](./examples/llm%20agent%20OR%20llm%20tool%20integration.md) -- [A Systematic Review of Pitman-Yor Language Model](./examples/Pitman-Yor%20Language%20Model.md) -- [A Systematic Review of Programming Testing Arxiv](./examples/programming%20testing%20arxiv.md): I wanted to limit my search to arXiv, so I included "arxiv" in the query, resulting in an unintended title. diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/examples/research_projects/rdm/retriever.py b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/examples/research_projects/rdm/retriever.py deleted file mode 100644 index 16518ed1bc42f85565b584bf11b843d00dc220bc..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/examples/research_projects/rdm/retriever.py +++ /dev/null @@ -1,250 +0,0 @@ -import os -from typing import List - -import faiss -import numpy as np -import torch -from datasets import Dataset, load_dataset -from PIL import Image -from transformers import CLIPFeatureExtractor, CLIPModel, PretrainedConfig - -from diffusers import logging - - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - - -def normalize_images(images: List[Image.Image]): - images = [np.array(image) for image in images] - images = [image / 127.5 - 1 for image in images] - return images - - -def preprocess_images(images: List[np.array], feature_extractor: CLIPFeatureExtractor) -> torch.FloatTensor: - """ - Preprocesses a list of images into a batch of tensors. - - Args: - images (:obj:`List[Image.Image]`): - A list of images to preprocess. - - Returns: - :obj:`torch.FloatTensor`: A batch of tensors. - """ - images = [np.array(image) for image in images] - images = [(image + 1.0) / 2.0 for image in images] - images = feature_extractor(images, return_tensors="pt").pixel_values - return images - - -class IndexConfig(PretrainedConfig): - def __init__( - self, - clip_name_or_path="openai/clip-vit-large-patch14", - dataset_name="Isamu136/oxford_pets_with_l14_emb", - image_column="image", - index_name="embeddings", - index_path=None, - dataset_set="train", - metric_type=faiss.METRIC_L2, - faiss_device=-1, - **kwargs, - ): - super().__init__(**kwargs) - self.clip_name_or_path = clip_name_or_path - self.dataset_name = dataset_name - self.image_column = image_column - self.index_name = index_name - self.index_path = index_path - self.dataset_set = dataset_set - self.metric_type = metric_type - self.faiss_device = faiss_device - - -class Index: - """ - Each index for a retrieval model is specific to the clip model used and the dataset used. - """ - - def __init__(self, config: IndexConfig, dataset: Dataset): - self.config = config - self.dataset = dataset - self.index_initialized = False - self.index_name = config.index_name - self.index_path = config.index_path - self.init_index() - - def set_index_name(self, index_name: str): - self.index_name = index_name - - def init_index(self): - if not self.index_initialized: - if self.index_path and self.index_name: - try: - self.dataset.add_faiss_index( - column=self.index_name, metric_type=self.config.metric_type, device=self.config.faiss_device - ) - self.index_initialized = True - except Exception as e: - print(e) - logger.info("Index not initialized") - if self.index_name in self.dataset.features: - self.dataset.add_faiss_index(column=self.index_name) - self.index_initialized = True - - def build_index( - self, - model=None, - feature_extractor: CLIPFeatureExtractor = None, - torch_dtype=torch.float32, - ): - if not self.index_initialized: - model = model or CLIPModel.from_pretrained(self.config.clip_name_or_path).to(dtype=torch_dtype) - feature_extractor = feature_extractor or CLIPFeatureExtractor.from_pretrained( - self.config.clip_name_or_path - ) - self.dataset = get_dataset_with_emb_from_clip_model( - self.dataset, - model, - feature_extractor, - image_column=self.config.image_column, - index_name=self.config.index_name, - ) - self.init_index() - - def retrieve_imgs(self, vec, k: int = 20): - vec = np.array(vec).astype(np.float32) - return self.dataset.get_nearest_examples(self.index_name, vec, k=k) - - def retrieve_imgs_batch(self, vec, k: int = 20): - vec = np.array(vec).astype(np.float32) - return self.dataset.get_nearest_examples_batch(self.index_name, vec, k=k) - - def retrieve_indices(self, vec, k: int = 20): - vec = np.array(vec).astype(np.float32) - return self.dataset.search(self.index_name, vec, k=k) - - def retrieve_indices_batch(self, vec, k: int = 20): - vec = np.array(vec).astype(np.float32) - return self.dataset.search_batch(self.index_name, vec, k=k) - - -class Retriever: - def __init__( - self, - config: IndexConfig, - index: Index = None, - dataset: Dataset = None, - model=None, - feature_extractor: CLIPFeatureExtractor = None, - ): - self.config = config - self.index = index or self._build_index(config, dataset, model=model, feature_extractor=feature_extractor) - - @classmethod - def from_pretrained( - cls, - retriever_name_or_path: str, - index: Index = None, - dataset: Dataset = None, - model=None, - feature_extractor: CLIPFeatureExtractor = None, - **kwargs, - ): - config = kwargs.pop("config", None) or IndexConfig.from_pretrained(retriever_name_or_path, **kwargs) - return cls(config, index=index, dataset=dataset, model=model, feature_extractor=feature_extractor) - - @staticmethod - def _build_index( - config: IndexConfig, dataset: Dataset = None, model=None, feature_extractor: CLIPFeatureExtractor = None - ): - dataset = dataset or load_dataset(config.dataset_name) - dataset = dataset[config.dataset_set] - index = Index(config, dataset) - index.build_index(model=model, feature_extractor=feature_extractor) - return index - - def save_pretrained(self, save_directory): - os.makedirs(save_directory, exist_ok=True) - if self.config.index_path is None: - index_path = os.path.join(save_directory, "hf_dataset_index.faiss") - self.index.dataset.get_index(self.config.index_name).save(index_path) - self.config.index_path = index_path - self.config.save_pretrained(save_directory) - - def init_retrieval(self): - logger.info("initializing retrieval") - self.index.init_index() - - def retrieve_imgs(self, embeddings: np.ndarray, k: int): - return self.index.retrieve_imgs(embeddings, k) - - def retrieve_imgs_batch(self, embeddings: np.ndarray, k: int): - return self.index.retrieve_imgs_batch(embeddings, k) - - def retrieve_indices(self, embeddings: np.ndarray, k: int): - return self.index.retrieve_indices(embeddings, k) - - def retrieve_indices_batch(self, embeddings: np.ndarray, k: int): - return self.index.retrieve_indices_batch(embeddings, k) - - def __call__( - self, - embeddings, - k: int = 20, - ): - return self.index.retrieve_imgs(embeddings, k) - - -def map_txt_to_clip_feature(clip_model, tokenizer, prompt): - text_inputs = tokenizer( - prompt, - padding="max_length", - max_length=tokenizer.model_max_length, - return_tensors="pt", - ) - text_input_ids = text_inputs.input_ids - - if text_input_ids.shape[-1] > tokenizer.model_max_length: - removed_text = tokenizer.batch_decode(text_input_ids[:, tokenizer.model_max_length :]) - logger.warning( - "The following part of your input was truncated because CLIP can only handle sequences up to" - f" {tokenizer.model_max_length} tokens: {removed_text}" - ) - text_input_ids = text_input_ids[:, : tokenizer.model_max_length] - text_embeddings = clip_model.get_text_features(text_input_ids.to(clip_model.device)) - text_embeddings = text_embeddings / torch.linalg.norm(text_embeddings, dim=-1, keepdim=True) - text_embeddings = text_embeddings[:, None, :] - return text_embeddings[0][0].cpu().detach().numpy() - - -def map_img_to_model_feature(model, feature_extractor, imgs, device): - for i, image in enumerate(imgs): - if not image.mode == "RGB": - imgs[i] = image.convert("RGB") - imgs = normalize_images(imgs) - retrieved_images = preprocess_images(imgs, feature_extractor).to(device) - image_embeddings = model(retrieved_images) - image_embeddings = image_embeddings / torch.linalg.norm(image_embeddings, dim=-1, keepdim=True) - image_embeddings = image_embeddings[None, ...] - return image_embeddings.cpu().detach().numpy()[0][0] - - -def get_dataset_with_emb_from_model(dataset, model, feature_extractor, image_column="image", index_name="embeddings"): - return dataset.map( - lambda example: { - index_name: map_img_to_model_feature(model, feature_extractor, [example[image_column]], model.device) - } - ) - - -def get_dataset_with_emb_from_clip_model( - dataset, clip_model, feature_extractor, image_column="image", index_name="embeddings" -): - return dataset.map( - lambda example: { - index_name: map_img_to_model_feature( - clip_model.get_image_features, feature_extractor, [example[image_column]], clip_model.device - ) - } - ) diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/optimization.py b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/optimization.py deleted file mode 100644 index 46e6125a0f5565b80ced30dfc147f8168ef35a5c..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/optimization.py +++ /dev/null @@ -1,354 +0,0 @@ -# coding=utf-8 -# Copyright 2023 The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""PyTorch optimization for diffusion models.""" - -import math -from enum import Enum -from typing import Optional, Union - -from torch.optim import Optimizer -from torch.optim.lr_scheduler import LambdaLR - -from .utils import logging - - -logger = logging.get_logger(__name__) - - -class SchedulerType(Enum): - LINEAR = "linear" - COSINE = "cosine" - COSINE_WITH_RESTARTS = "cosine_with_restarts" - POLYNOMIAL = "polynomial" - CONSTANT = "constant" - CONSTANT_WITH_WARMUP = "constant_with_warmup" - PIECEWISE_CONSTANT = "piecewise_constant" - - -def get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1): - """ - Create a schedule with a constant learning rate, using the learning rate set in optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - """ - return LambdaLR(optimizer, lambda _: 1, last_epoch=last_epoch) - - -def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1): - """ - Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate - increases linearly between 0 and the initial lr set in the optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - num_warmup_steps (`int`): - The number of steps for the warmup phase. - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - """ - - def lr_lambda(current_step: int): - if current_step < num_warmup_steps: - return float(current_step) / float(max(1.0, num_warmup_steps)) - return 1.0 - - return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch) - - -def get_piecewise_constant_schedule(optimizer: Optimizer, step_rules: str, last_epoch: int = -1): - """ - Create a schedule with a constant learning rate, using the learning rate set in optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - step_rules (`string`): - The rules for the learning rate. ex: rule_steps="1:10,0.1:20,0.01:30,0.005" it means that the learning rate - if multiple 1 for the first 10 steps, mutiple 0.1 for the next 20 steps, multiple 0.01 for the next 30 - steps and multiple 0.005 for the other steps. - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - """ - - rules_dict = {} - rule_list = step_rules.split(",") - for rule_str in rule_list[:-1]: - value_str, steps_str = rule_str.split(":") - steps = int(steps_str) - value = float(value_str) - rules_dict[steps] = value - last_lr_multiple = float(rule_list[-1]) - - def create_rules_function(rules_dict, last_lr_multiple): - def rule_func(steps: int) -> float: - sorted_steps = sorted(rules_dict.keys()) - for i, sorted_step in enumerate(sorted_steps): - if steps < sorted_step: - return rules_dict[sorted_steps[i]] - return last_lr_multiple - - return rule_func - - rules_func = create_rules_function(rules_dict, last_lr_multiple) - - return LambdaLR(optimizer, rules_func, last_epoch=last_epoch) - - -def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): - """ - Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after - a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - num_warmup_steps (`int`): - The number of steps for the warmup phase. - num_training_steps (`int`): - The total number of training steps. - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - """ - - def lr_lambda(current_step: int): - if current_step < num_warmup_steps: - return float(current_step) / float(max(1, num_warmup_steps)) - return max( - 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) - ) - - return LambdaLR(optimizer, lr_lambda, last_epoch) - - -def get_cosine_schedule_with_warmup( - optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1 -): - """ - Create a schedule with a learning rate that decreases following the values of the cosine function between the - initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the - initial lr set in the optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - num_warmup_steps (`int`): - The number of steps for the warmup phase. - num_training_steps (`int`): - The total number of training steps. - num_periods (`float`, *optional*, defaults to 0.5): - The number of periods of the cosine function in a schedule (the default is to just decrease from the max - value to 0 following a half-cosine). - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - """ - - def lr_lambda(current_step): - if current_step < num_warmup_steps: - return float(current_step) / float(max(1, num_warmup_steps)) - progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) - return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) - - return LambdaLR(optimizer, lr_lambda, last_epoch) - - -def get_cosine_with_hard_restarts_schedule_with_warmup( - optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1 -): - """ - Create a schedule with a learning rate that decreases following the values of the cosine function between the - initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases - linearly between 0 and the initial lr set in the optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - num_warmup_steps (`int`): - The number of steps for the warmup phase. - num_training_steps (`int`): - The total number of training steps. - num_cycles (`int`, *optional*, defaults to 1): - The number of hard restarts to use. - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - """ - - def lr_lambda(current_step): - if current_step < num_warmup_steps: - return float(current_step) / float(max(1, num_warmup_steps)) - progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) - if progress >= 1.0: - return 0.0 - return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0)))) - - return LambdaLR(optimizer, lr_lambda, last_epoch) - - -def get_polynomial_decay_schedule_with_warmup( - optimizer, num_warmup_steps, num_training_steps, lr_end=1e-7, power=1.0, last_epoch=-1 -): - """ - Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the - optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the - initial lr set in the optimizer. - - Args: - optimizer ([`~torch.optim.Optimizer`]): - The optimizer for which to schedule the learning rate. - num_warmup_steps (`int`): - The number of steps for the warmup phase. - num_training_steps (`int`): - The total number of training steps. - lr_end (`float`, *optional*, defaults to 1e-7): - The end LR. - power (`float`, *optional*, defaults to 1.0): - Power factor. - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - - Note: *power* defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT - implementation at - https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37 - - Return: - `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. - - """ - - lr_init = optimizer.defaults["lr"] - if not (lr_init > lr_end): - raise ValueError(f"lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})") - - def lr_lambda(current_step: int): - if current_step < num_warmup_steps: - return float(current_step) / float(max(1, num_warmup_steps)) - elif current_step > num_training_steps: - return lr_end / lr_init # as LambdaLR multiplies by lr_init - else: - lr_range = lr_init - lr_end - decay_steps = num_training_steps - num_warmup_steps - pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps - decay = lr_range * pct_remaining**power + lr_end - return decay / lr_init # as LambdaLR multiplies by lr_init - - return LambdaLR(optimizer, lr_lambda, last_epoch) - - -TYPE_TO_SCHEDULER_FUNCTION = { - SchedulerType.LINEAR: get_linear_schedule_with_warmup, - SchedulerType.COSINE: get_cosine_schedule_with_warmup, - SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, - SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, - SchedulerType.CONSTANT: get_constant_schedule, - SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, - SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, -} - - -def get_scheduler( - name: Union[str, SchedulerType], - optimizer: Optimizer, - step_rules: Optional[str] = None, - num_warmup_steps: Optional[int] = None, - num_training_steps: Optional[int] = None, - num_cycles: int = 1, - power: float = 1.0, - last_epoch: int = -1, -): - """ - Unified API to get any scheduler from its name. - - Args: - name (`str` or `SchedulerType`): - The name of the scheduler to use. - optimizer (`torch.optim.Optimizer`): - The optimizer that will be used during training. - step_rules (`str`, *optional*): - A string representing the step rules to use. This is only used by the `PIECEWISE_CONSTANT` scheduler. - num_warmup_steps (`int`, *optional*): - The number of warmup steps to do. This is not required by all schedulers (hence the argument being - optional), the function will raise an error if it's unset and the scheduler type requires it. - num_training_steps (`int``, *optional*): - The number of training steps to do. This is not required by all schedulers (hence the argument being - optional), the function will raise an error if it's unset and the scheduler type requires it. - num_cycles (`int`, *optional*): - The number of hard restarts used in `COSINE_WITH_RESTARTS` scheduler. - power (`float`, *optional*, defaults to 1.0): - Power factor. See `POLYNOMIAL` scheduler - last_epoch (`int`, *optional*, defaults to -1): - The index of the last epoch when resuming training. - """ - name = SchedulerType(name) - schedule_func = TYPE_TO_SCHEDULER_FUNCTION[name] - if name == SchedulerType.CONSTANT: - return schedule_func(optimizer, last_epoch=last_epoch) - - if name == SchedulerType.PIECEWISE_CONSTANT: - return schedule_func(optimizer, step_rules=step_rules, last_epoch=last_epoch) - - # All other schedulers require `num_warmup_steps` - if num_warmup_steps is None: - raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument.") - - if name == SchedulerType.CONSTANT_WITH_WARMUP: - return schedule_func(optimizer, num_warmup_steps=num_warmup_steps, last_epoch=last_epoch) - - # All other schedulers require `num_training_steps` - if num_training_steps is None: - raise ValueError(f"{name} requires `num_training_steps`, please provide that argument.") - - if name == SchedulerType.COSINE_WITH_RESTARTS: - return schedule_func( - optimizer, - num_warmup_steps=num_warmup_steps, - num_training_steps=num_training_steps, - num_cycles=num_cycles, - last_epoch=last_epoch, - ) - - if name == SchedulerType.POLYNOMIAL: - return schedule_func( - optimizer, - num_warmup_steps=num_warmup_steps, - num_training_steps=num_training_steps, - power=power, - last_epoch=last_epoch, - ) - - return schedule_func( - optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, last_epoch=last_epoch - ) diff --git a/spaces/parkyzh/bingo/src/components/button-scroll-to-bottom.tsx b/spaces/parkyzh/bingo/src/components/button-scroll-to-bottom.tsx deleted file mode 100644 index b68ab9c0e48320c356e51a52d11b9ca63909e6c5..0000000000000000000000000000000000000000 --- a/spaces/parkyzh/bingo/src/components/button-scroll-to-bottom.tsx +++ /dev/null @@ -1,34 +0,0 @@ -'use client' - -import * as React from 'react' - -import { cn } from '@/lib/utils' -import { useAtBottom } from '@/lib/hooks/use-at-bottom' -import { Button, type ButtonProps } from '@/components/ui/button' -import { IconArrowDown } from '@/components/ui/icons' - -export function ButtonScrollToBottom({ className, ...props }: ButtonProps) { - const isAtBottom = useAtBottom() - - return ( - - ) -} diff --git a/spaces/patgpt4/MusicGen/tests/modules/test_transformer.py b/spaces/patgpt4/MusicGen/tests/modules/test_transformer.py deleted file mode 100644 index d6092963d275ba101e016fd448fd0b456d918c27..0000000000000000000000000000000000000000 --- a/spaces/patgpt4/MusicGen/tests/modules/test_transformer.py +++ /dev/null @@ -1,253 +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. - -from itertools import product - -import pytest -import torch - -from audiocraft.modules.transformer import ( - StreamingMultiheadAttention, StreamingTransformer, set_efficient_attention_backend) - - -def test_transformer_causal_streaming(): - torch.manual_seed(1234) - - for context, custom in product([None, 10], [False, True]): - # Test that causality and receptive fields are properly handled. - # looking at the gradients - tr = StreamingTransformer( - 16, 4, 1 if context else 2, - causal=True, past_context=context, custom=custom, - dropout=0.) - steps = 20 - for k in [0, 10, 15, 19]: - x = torch.randn(4, steps, 16, requires_grad=True) - y = tr(x) - y[:, k].abs().sum().backward() - if k + 1 < steps: - assert torch.allclose(x.grad[:, k + 1:], torch.tensor(0.)), x.grad[:, k + 1:].norm() - assert not torch.allclose(x.grad[:, :k + 1], torch.tensor(0.)), x.grad[:, :k + 1].norm() - if context is not None and k > context: - limit = k - context - 1 - assert torch.allclose(x.grad[:, :limit], - torch.tensor(0.)), x.grad[:, :limit].norm() - - # Now check that streaming gives the same result at batch eval. - x = torch.randn(4, steps, 16) - y = tr(x) - ys = [] - with tr.streaming(): - for k in range(steps): - chunk = x[:, k:k + 1, :] - ys.append(tr(chunk)) - y_stream = torch.cat(ys, dim=1) - delta = torch.norm(y_stream - y) / torch.norm(y) - assert delta < 1e-6, delta - - -def test_transformer_vs_pytorch(): - torch.manual_seed(1234) - # Check that in the non causal setting, we get the same result as - # PyTorch Transformer encoder. - for custom in [False, True]: - tr = StreamingTransformer( - 16, 4, 2, - causal=False, custom=custom, dropout=0., positional_scale=0.) - layer = torch.nn.TransformerEncoderLayer(16, 4, dropout=0., batch_first=True) - tr_ref = torch.nn.TransformerEncoder(layer, 2) - tr.load_state_dict(tr_ref.state_dict()) - - x = torch.randn(4, 20, 16) - y = tr(x) - y2 = tr_ref(x) - delta = torch.norm(y2 - y) / torch.norm(y) - assert delta < 1e-6, delta - - -def test_streaming_api(): - tr = StreamingTransformer(16, 4, 2, causal=True, dropout=0.) - tr.eval() - steps = 12 - x = torch.randn(1, steps, 16) - - with torch.no_grad(): - with tr.streaming(): - _ = tr(x[:, :1]) - state = {k: v.clone() for k, v in tr.get_streaming_state().items()} - y = tr(x[:, 1:2]) - tr.set_streaming_state(state) - y2 = tr(x[:, 1:2]) - assert torch.allclose(y, y2), (y - y2).norm() - assert tr.flush() is None - - -def test_memory_efficient(): - torch.manual_seed(1234) - for backend in ['torch', 'xformers']: - set_efficient_attention_backend(backend) - - tr = StreamingTransformer( - 16, 4, 2, custom=True, dropout=0., layer_scale=0.1) - tr_mem_efficient = StreamingTransformer( - 16, 4, 2, dropout=0., memory_efficient=True, layer_scale=0.1) - tr_mem_efficient.load_state_dict(tr.state_dict()) - tr.eval() - steps = 12 - x = torch.randn(3, steps, 16) - - with torch.no_grad(): - y = tr(x) - y2 = tr_mem_efficient(x) - assert torch.allclose(y, y2), ((y - y2).norm(), backend) - - -def test_attention_as_float32(): - torch.manual_seed(1234) - cases = [ - {'custom': True}, - {'custom': False}, - ] - for case in cases: - tr = StreamingTransformer(16, 4, 2, dropout=0., dtype=torch.bfloat16, **case) - tr_float32 = StreamingTransformer( - 16, 4, 2, dropout=0., attention_as_float32=True, dtype=torch.bfloat16, **case) - if not case['custom']: - # we are not using autocast here because it doesn't really - # work as expected on CPU, so we have to manually cast the weights of the MHA. - for layer in tr_float32.layers: - layer.self_attn.mha.to(torch.float32) - tr_float32.load_state_dict(tr.state_dict()) - steps = 12 - x = torch.randn(3, steps, 16, dtype=torch.bfloat16) - - with torch.no_grad(): - y = tr(x) - y2 = tr_float32(x) - assert not torch.allclose(y, y2), (y - y2).norm() - - -@torch.no_grad() -def test_streaming_memory_efficient(): - torch.manual_seed(1234) - for backend in ['torch', 'xformers']: - set_efficient_attention_backend(backend) - tr = StreamingTransformer(16, 4, 2, causal=True, dropout=0., custom=True) - tr_mem_efficient = StreamingTransformer( - 16, 4, 2, dropout=0., memory_efficient=True, causal=True) - tr.load_state_dict(tr_mem_efficient.state_dict()) - tr.eval() - tr_mem_efficient.eval() - steps = 12 - x = torch.randn(3, steps, 16) - - ref = tr(x) - - with tr_mem_efficient.streaming(): - outs = [] - # frame_sizes = [2] + [1] * (steps - 2) - frame_sizes = [1] * steps - - for frame_size in frame_sizes: - frame = x[:, :frame_size] - x = x[:, frame_size:] - outs.append(tr_mem_efficient(frame)) - - out = torch.cat(outs, dim=1) - delta = torch.norm(out - ref) / torch.norm(out) - assert delta < 1e-6, delta - - -def test_cross_attention(): - torch.manual_seed(1234) - for norm_first in [True, False]: - m = StreamingTransformer( - 16, 4, 2, cross_attention=False, norm_first=norm_first, dropout=0., custom=True) - m_cross = StreamingTransformer( - 16, 4, 2, cross_attention=True, norm_first=norm_first, dropout=0., custom=True) - m_cross.load_state_dict(m.state_dict(), strict=False) - x = torch.randn(2, 5, 16) - cross_x = torch.randn(2, 3, 16) - y_ref = m(x) - y_cross_zero = m_cross(x, cross_attention_src=0 * cross_x) - # With norm_first, the two should be exactly yhe same, - # but with norm_first=False, we get 2 normalization in a row - # and the epsilon value leads to a tiny change. - atol = 0. if norm_first else 1e-6 - print((y_ref - y_cross_zero).norm() / y_ref.norm()) - assert torch.allclose(y_ref, y_cross_zero, atol=atol) - - # We now expect a difference even with a generous atol of 1e-2. - y_cross = m_cross(x, cross_attention_src=cross_x) - assert not torch.allclose(y_cross, y_cross_zero, atol=1e-2) - - with pytest.raises(AssertionError): - _ = m_cross(x) - _ = m(x, cross_attention_src=cross_x) - - -def test_cross_attention_compat(): - torch.manual_seed(1234) - num_heads = 2 - dim = num_heads * 64 - with pytest.raises(AssertionError): - StreamingMultiheadAttention(dim, num_heads, causal=True, cross_attention=True) - - cross_attn = StreamingMultiheadAttention( - dim, num_heads, dropout=0, cross_attention=True, custom=True) - ref_attn = torch.nn.MultiheadAttention(dim, num_heads, dropout=0, batch_first=True) - - # We can load the regular attention state dict - # so we have compat when loading old checkpoints. - cross_attn.load_state_dict(ref_attn.state_dict()) - - queries = torch.randn(3, 7, dim) - keys = torch.randn(3, 9, dim) - values = torch.randn(3, 9, dim) - - y = cross_attn(queries, keys, values)[0] - y_ref = ref_attn(queries, keys, values)[0] - assert torch.allclose(y, y_ref, atol=1e-7), (y - y_ref).norm() / y_ref.norm() - - # Now let's check that streaming is working properly. - with cross_attn.streaming(): - ys = [] - for step in range(queries.shape[1]): - ys.append(cross_attn(queries[:, step: step + 1], keys, values)[0]) - y_streaming = torch.cat(ys, dim=1) - assert torch.allclose(y_streaming, y, atol=1e-7) - - -def test_repeat_kv(): - torch.manual_seed(1234) - num_heads = 8 - kv_repeat = 4 - dim = num_heads * 64 - with pytest.raises(AssertionError): - mha = StreamingMultiheadAttention( - dim, num_heads, causal=True, kv_repeat=kv_repeat, cross_attention=True) - mha = StreamingMultiheadAttention( - dim, num_heads, causal=True, kv_repeat=kv_repeat) - mha = StreamingMultiheadAttention( - dim, num_heads, causal=True, kv_repeat=kv_repeat, custom=True) - x = torch.randn(4, 18, dim) - y = mha(x, x, x)[0] - assert x.shape == y.shape - - -def test_qk_layer_norm(): - torch.manual_seed(1234) - tr = StreamingTransformer( - 16, 4, 2, custom=True, dropout=0., qk_layer_norm=True, bias_attn=False) - steps = 12 - x = torch.randn(3, steps, 16) - y = tr(x) - - tr = StreamingTransformer( - 16, 4, 2, custom=True, dropout=0., qk_layer_norm=True, cross_attention=True) - z = torch.randn(3, 21, 16) - y = tr(x, cross_attention_src=z) - assert y.shape == x.shape diff --git a/spaces/perilli/tortoise-tts-v2/utils/tokenizer.py b/spaces/perilli/tortoise-tts-v2/utils/tokenizer.py deleted file mode 100644 index ed7e4cdf079f59c75b38e5b6cfa77c652d23618b..0000000000000000000000000000000000000000 --- a/spaces/perilli/tortoise-tts-v2/utils/tokenizer.py +++ /dev/null @@ -1,187 +0,0 @@ -import re - -import inflect -import torch -from tokenizers import Tokenizer - - -# Regular expression matching whitespace: -from unidecode import unidecode - -_whitespace_re = re.compile(r'\s+') - - -# List of (regular expression, replacement) pairs for abbreviations: -_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [ - ('mrs', 'misess'), - ('mr', 'mister'), - ('dr', 'doctor'), - ('st', 'saint'), - ('co', 'company'), - ('jr', 'junior'), - ('maj', 'major'), - ('gen', 'general'), - ('drs', 'doctors'), - ('rev', 'reverend'), - ('lt', 'lieutenant'), - ('hon', 'honorable'), - ('sgt', 'sergeant'), - ('capt', 'captain'), - ('esq', 'esquire'), - ('ltd', 'limited'), - ('col', 'colonel'), - ('ft', 'fort'), -]] - - -def expand_abbreviations(text): - for regex, replacement in _abbreviations: - text = re.sub(regex, replacement, text) - return text - - -_inflect = inflect.engine() -_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') -_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') -_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') -_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') -_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)') -_number_re = re.compile(r'[0-9]+') - - -def _remove_commas(m): - return m.group(1).replace(',', '') - - -def _expand_decimal_point(m): - return m.group(1).replace('.', ' point ') - - -def _expand_dollars(m): - match = m.group(1) - parts = match.split('.') - if len(parts) > 2: - return match + ' dollars' # Unexpected format - dollars = int(parts[0]) if parts[0] else 0 - cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0 - if dollars and cents: - dollar_unit = 'dollar' if dollars == 1 else 'dollars' - cent_unit = 'cent' if cents == 1 else 'cents' - return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit) - elif dollars: - dollar_unit = 'dollar' if dollars == 1 else 'dollars' - return '%s %s' % (dollars, dollar_unit) - elif cents: - cent_unit = 'cent' if cents == 1 else 'cents' - return '%s %s' % (cents, cent_unit) - else: - return 'zero dollars' - - -def _expand_ordinal(m): - return _inflect.number_to_words(m.group(0)) - - -def _expand_number(m): - num = int(m.group(0)) - if num > 1000 and num < 3000: - if num == 2000: - return 'two thousand' - elif num > 2000 and num < 2010: - return 'two thousand ' + _inflect.number_to_words(num % 100) - elif num % 100 == 0: - return _inflect.number_to_words(num // 100) + ' hundred' - else: - return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ') - else: - return _inflect.number_to_words(num, andword='') - - -def normalize_numbers(text): - text = re.sub(_comma_number_re, _remove_commas, text) - text = re.sub(_pounds_re, r'\1 pounds', text) - text = re.sub(_dollars_re, _expand_dollars, text) - text = re.sub(_decimal_number_re, _expand_decimal_point, text) - text = re.sub(_ordinal_re, _expand_ordinal, text) - text = re.sub(_number_re, _expand_number, text) - return text - - -def expand_numbers(text): - return normalize_numbers(text) - - -def lowercase(text): - return text.lower() - - -def collapse_whitespace(text): - return re.sub(_whitespace_re, ' ', text) - - -def convert_to_ascii(text): - return unidecode(text) - - -def basic_cleaners(text): - '''Basic pipeline that lowercases and collapses whitespace without transliteration.''' - text = lowercase(text) - text = collapse_whitespace(text) - return text - - -def transliteration_cleaners(text): - '''Pipeline for non-English text that transliterates to ASCII.''' - text = convert_to_ascii(text) - text = lowercase(text) - text = collapse_whitespace(text) - return text - - -def english_cleaners(text): - '''Pipeline for English text, including number and abbreviation expansion.''' - text = convert_to_ascii(text) - text = lowercase(text) - text = expand_numbers(text) - text = expand_abbreviations(text) - text = collapse_whitespace(text) - text = text.replace('"', '') - return text - -def lev_distance(s1, s2): - if len(s1) > len(s2): - s1, s2 = s2, s1 - - distances = range(len(s1) + 1) - for i2, c2 in enumerate(s2): - distances_ = [i2 + 1] - for i1, c1 in enumerate(s1): - if c1 == c2: - distances_.append(distances[i1]) - else: - distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1]))) - distances = distances_ - return distances[-1] - -class VoiceBpeTokenizer: - def __init__(self, vocab_file='data/tokenizer.json'): - if vocab_file is not None: - self.tokenizer = Tokenizer.from_file(vocab_file) - - def preprocess_text(self, txt): - txt = english_cleaners(txt) - return txt - - def encode(self, txt): - txt = self.preprocess_text(txt) - txt = txt.replace(' ', '[SPACE]') - return self.tokenizer.encode(txt).ids - - def decode(self, seq): - if isinstance(seq, torch.Tensor): - seq = seq.cpu().numpy() - txt = self.tokenizer.decode(seq, skip_special_tokens=False).replace(' ', '') - txt = txt.replace('[SPACE]', ' ') - txt = txt.replace('[STOP]', '') - txt = txt.replace('[UNK]', '') - return txt \ No newline at end of file diff --git a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/resolvelib/reporters.py b/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/resolvelib/reporters.py deleted file mode 100644 index 688b5e10d8608fdb324c5df0ec3d9f4aa720de0e..0000000000000000000000000000000000000000 --- a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/resolvelib/reporters.py +++ /dev/null @@ -1,43 +0,0 @@ -class BaseReporter(object): - """Delegate class to provider progress reporting for the resolver.""" - - def starting(self): - """Called before the resolution actually starts.""" - - def starting_round(self, index): - """Called before each round of resolution starts. - - The index is zero-based. - """ - - def ending_round(self, index, state): - """Called before each round of resolution ends. - - This is NOT called if the resolution ends at this round. Use `ending` - if you want to report finalization. The index is zero-based. - """ - - def ending(self, state): - """Called before the resolution ends successfully.""" - - def adding_requirement(self, requirement, parent): - """Called when adding a new requirement into the resolve criteria. - - :param requirement: The additional requirement to be applied to filter - the available candidaites. - :param parent: The candidate that requires ``requirement`` as a - dependency, or None if ``requirement`` is one of the root - requirements passed in from ``Resolver.resolve()``. - """ - - def resolving_conflicts(self, causes): - """Called when starting to attempt requirement conflict resolution. - - :param causes: The information on the collision that caused the backtracking. - """ - - def rejecting_candidate(self, criterion, candidate): - """Called when rejecting a candidate during backtracking.""" - - def pinning(self, candidate): - """Called when adding a candidate to the potential solution.""" diff --git a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/typing_extensions.py b/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/typing_extensions.py deleted file mode 100644 index 4f93acffbdc1d8ba9555114c190e44140c34c291..0000000000000000000000000000000000000000 --- a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/typing_extensions.py +++ /dev/null @@ -1,3072 +0,0 @@ -import abc -import collections -import collections.abc -import functools -import inspect -import operator -import sys -import types as _types -import typing -import warnings - -__all__ = [ - # Super-special typing primitives. - 'Any', - 'ClassVar', - 'Concatenate', - 'Final', - 'LiteralString', - 'ParamSpec', - 'ParamSpecArgs', - 'ParamSpecKwargs', - 'Self', - 'Type', - 'TypeVar', - 'TypeVarTuple', - 'Unpack', - - # ABCs (from collections.abc). - 'Awaitable', - 'AsyncIterator', - 'AsyncIterable', - 'Coroutine', - 'AsyncGenerator', - 'AsyncContextManager', - 'Buffer', - 'ChainMap', - - # Concrete collection types. - 'ContextManager', - 'Counter', - 'Deque', - 'DefaultDict', - 'NamedTuple', - 'OrderedDict', - 'TypedDict', - - # Structural checks, a.k.a. protocols. - 'SupportsAbs', - 'SupportsBytes', - 'SupportsComplex', - 'SupportsFloat', - 'SupportsIndex', - 'SupportsInt', - 'SupportsRound', - - # One-off things. - 'Annotated', - 'assert_never', - 'assert_type', - 'clear_overloads', - 'dataclass_transform', - 'deprecated', - 'get_overloads', - 'final', - 'get_args', - 'get_origin', - 'get_original_bases', - 'get_protocol_members', - 'get_type_hints', - 'IntVar', - 'is_protocol', - 'is_typeddict', - 'Literal', - 'NewType', - 'overload', - 'override', - 'Protocol', - 'reveal_type', - 'runtime', - 'runtime_checkable', - 'Text', - 'TypeAlias', - 'TypeAliasType', - 'TypeGuard', - 'TYPE_CHECKING', - 'Never', - 'NoReturn', - 'Required', - 'NotRequired', - - # Pure aliases, have always been in typing - 'AbstractSet', - 'AnyStr', - 'BinaryIO', - 'Callable', - 'Collection', - 'Container', - 'Dict', - 'ForwardRef', - 'FrozenSet', - 'Generator', - 'Generic', - 'Hashable', - 'IO', - 'ItemsView', - 'Iterable', - 'Iterator', - 'KeysView', - 'List', - 'Mapping', - 'MappingView', - 'Match', - 'MutableMapping', - 'MutableSequence', - 'MutableSet', - 'Optional', - 'Pattern', - 'Reversible', - 'Sequence', - 'Set', - 'Sized', - 'TextIO', - 'Tuple', - 'Union', - 'ValuesView', - 'cast', - 'no_type_check', - 'no_type_check_decorator', -] - -# for backward compatibility -PEP_560 = True -GenericMeta = type - -# The functions below are modified copies of typing internal helpers. -# They are needed by _ProtocolMeta and they provide support for PEP 646. - - -class _Sentinel: - def __repr__(self): - return "" - - -_marker = _Sentinel() - - -def _check_generic(cls, parameters, elen=_marker): - """Check correct count for parameters of a generic cls (internal helper). - This gives a nice error message in case of count mismatch. - """ - if not elen: - raise TypeError(f"{cls} is not a generic class") - if elen is _marker: - if not hasattr(cls, "__parameters__") or not cls.__parameters__: - raise TypeError(f"{cls} is not a generic class") - elen = len(cls.__parameters__) - alen = len(parameters) - if alen != elen: - if hasattr(cls, "__parameters__"): - parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] - num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) - if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): - return - raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};" - f" actual {alen}, expected {elen}") - - -if sys.version_info >= (3, 10): - def _should_collect_from_parameters(t): - return isinstance( - t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) - ) -elif sys.version_info >= (3, 9): - def _should_collect_from_parameters(t): - return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) -else: - def _should_collect_from_parameters(t): - return isinstance(t, typing._GenericAlias) and not t._special - - -def _collect_type_vars(types, typevar_types=None): - """Collect all type variable contained in types in order of - first appearance (lexicographic order). For example:: - - _collect_type_vars((T, List[S, T])) == (T, S) - """ - if typevar_types is None: - typevar_types = typing.TypeVar - tvars = [] - for t in types: - if ( - isinstance(t, typevar_types) and - t not in tvars and - not _is_unpack(t) - ): - tvars.append(t) - if _should_collect_from_parameters(t): - tvars.extend([t for t in t.__parameters__ if t not in tvars]) - return tuple(tvars) - - -NoReturn = typing.NoReturn - -# Some unconstrained type variables. These are used by the container types. -# (These are not for export.) -T = typing.TypeVar('T') # Any type. -KT = typing.TypeVar('KT') # Key type. -VT = typing.TypeVar('VT') # Value type. -T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. -T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. - - -if sys.version_info >= (3, 11): - from typing import Any -else: - - class _AnyMeta(type): - def __instancecheck__(self, obj): - if self is Any: - raise TypeError("typing_extensions.Any cannot be used with isinstance()") - return super().__instancecheck__(obj) - - def __repr__(self): - if self is Any: - return "typing_extensions.Any" - return super().__repr__() - - class Any(metaclass=_AnyMeta): - """Special type indicating an unconstrained type. - - Any is compatible with every type. - - Any assumed to have all methods. - - All values assumed to be instances of Any. - Note that all the above statements are true from the point of view of - static type checkers. At runtime, Any should not be used with instance - checks. - """ - def __new__(cls, *args, **kwargs): - if cls is Any: - raise TypeError("Any cannot be instantiated") - return super().__new__(cls, *args, **kwargs) - - -ClassVar = typing.ClassVar - - -class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): - def __repr__(self): - return 'typing_extensions.' + self._name - - -# On older versions of typing there is an internal class named "Final". -# 3.8+ -if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): - Final = typing.Final -# 3.7 -else: - class _FinalForm(_ExtensionsSpecialForm, _root=True): - def __getitem__(self, parameters): - item = typing._type_check(parameters, - f'{self._name} accepts only a single type.') - return typing._GenericAlias(self, (item,)) - - Final = _FinalForm('Final', - doc="""A special typing construct to indicate that a name - cannot be re-assigned or overridden in a subclass. - For example: - - MAX_SIZE: Final = 9000 - MAX_SIZE += 1 # Error reported by type checker - - class Connection: - TIMEOUT: Final[int] = 10 - class FastConnector(Connection): - TIMEOUT = 1 # Error reported by type checker - - There is no runtime checking of these properties.""") - -if sys.version_info >= (3, 11): - final = typing.final -else: - # @final exists in 3.8+, but we backport it for all versions - # before 3.11 to keep support for the __final__ attribute. - # See https://bugs.python.org/issue46342 - def final(f): - """This decorator can be used to indicate to type checkers that - the decorated method cannot be overridden, and decorated class - cannot be subclassed. For example: - - class Base: - @final - def done(self) -> None: - ... - class Sub(Base): - def done(self) -> None: # Error reported by type checker - ... - @final - class Leaf: - ... - class Other(Leaf): # Error reported by type checker - ... - - There is no runtime checking of these properties. The decorator - sets the ``__final__`` attribute to ``True`` on the decorated object - to allow runtime introspection. - """ - try: - f.__final__ = True - except (AttributeError, TypeError): - # Skip the attribute silently if it is not writable. - # AttributeError happens if the object has __slots__ or a - # read-only property, TypeError if it's a builtin class. - pass - return f - - -def IntVar(name): - return typing.TypeVar(name) - - -# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 -if sys.version_info >= (3, 10, 1): - Literal = typing.Literal -else: - def _flatten_literal_params(parameters): - """An internal helper for Literal creation: flatten Literals among parameters""" - params = [] - for p in parameters: - if isinstance(p, _LiteralGenericAlias): - params.extend(p.__args__) - else: - params.append(p) - return tuple(params) - - def _value_and_type_iter(params): - for p in params: - yield p, type(p) - - class _LiteralGenericAlias(typing._GenericAlias, _root=True): - def __eq__(self, other): - if not isinstance(other, _LiteralGenericAlias): - return NotImplemented - these_args_deduped = set(_value_and_type_iter(self.__args__)) - other_args_deduped = set(_value_and_type_iter(other.__args__)) - return these_args_deduped == other_args_deduped - - def __hash__(self): - return hash(frozenset(_value_and_type_iter(self.__args__))) - - class _LiteralForm(_ExtensionsSpecialForm, _root=True): - def __init__(self, doc: str): - self._name = 'Literal' - self._doc = self.__doc__ = doc - - def __getitem__(self, parameters): - if not isinstance(parameters, tuple): - parameters = (parameters,) - - parameters = _flatten_literal_params(parameters) - - val_type_pairs = list(_value_and_type_iter(parameters)) - try: - deduped_pairs = set(val_type_pairs) - except TypeError: - # unhashable parameters - pass - else: - # similar logic to typing._deduplicate on Python 3.9+ - if len(deduped_pairs) < len(val_type_pairs): - new_parameters = [] - for pair in val_type_pairs: - if pair in deduped_pairs: - new_parameters.append(pair[0]) - deduped_pairs.remove(pair) - assert not deduped_pairs, deduped_pairs - parameters = tuple(new_parameters) - - return _LiteralGenericAlias(self, parameters) - - Literal = _LiteralForm(doc="""\ - A type that can be used to indicate to type checkers - that the corresponding value has a value literally equivalent - to the provided parameter. For example: - - var: Literal[4] = 4 - - The type checker understands that 'var' is literally equal to - the value 4 and no other value. - - Literal[...] cannot be subclassed. There is no runtime - checking verifying that the parameter is actually a value - instead of a type.""") - - -_overload_dummy = typing._overload_dummy - - -if hasattr(typing, "get_overloads"): # 3.11+ - overload = typing.overload - get_overloads = typing.get_overloads - clear_overloads = typing.clear_overloads -else: - # {module: {qualname: {firstlineno: func}}} - _overload_registry = collections.defaultdict( - functools.partial(collections.defaultdict, dict) - ) - - def overload(func): - """Decorator for overloaded functions/methods. - - In a stub file, place two or more stub definitions for the same - function in a row, each decorated with @overload. For example: - - @overload - def utf8(value: None) -> None: ... - @overload - def utf8(value: bytes) -> bytes: ... - @overload - def utf8(value: str) -> bytes: ... - - In a non-stub file (i.e. a regular .py file), do the same but - follow it with an implementation. The implementation should *not* - be decorated with @overload. For example: - - @overload - def utf8(value: None) -> None: ... - @overload - def utf8(value: bytes) -> bytes: ... - @overload - def utf8(value: str) -> bytes: ... - def utf8(value): - # implementation goes here - - The overloads for a function can be retrieved at runtime using the - get_overloads() function. - """ - # classmethod and staticmethod - f = getattr(func, "__func__", func) - try: - _overload_registry[f.__module__][f.__qualname__][ - f.__code__.co_firstlineno - ] = func - except AttributeError: - # Not a normal function; ignore. - pass - return _overload_dummy - - def get_overloads(func): - """Return all defined overloads for *func* as a sequence.""" - # classmethod and staticmethod - f = getattr(func, "__func__", func) - if f.__module__ not in _overload_registry: - return [] - mod_dict = _overload_registry[f.__module__] - if f.__qualname__ not in mod_dict: - return [] - return list(mod_dict[f.__qualname__].values()) - - def clear_overloads(): - """Clear all overloads in the registry.""" - _overload_registry.clear() - - -# This is not a real generic class. Don't use outside annotations. -Type = typing.Type - -# Various ABCs mimicking those in collections.abc. -# A few are simply re-exported for completeness. - - -Awaitable = typing.Awaitable -Coroutine = typing.Coroutine -AsyncIterable = typing.AsyncIterable -AsyncIterator = typing.AsyncIterator -Deque = typing.Deque -ContextManager = typing.ContextManager -AsyncContextManager = typing.AsyncContextManager -DefaultDict = typing.DefaultDict - -# 3.7.2+ -if hasattr(typing, 'OrderedDict'): - OrderedDict = typing.OrderedDict -# 3.7.0-3.7.2 -else: - OrderedDict = typing._alias(collections.OrderedDict, (KT, VT)) - -Counter = typing.Counter -ChainMap = typing.ChainMap -AsyncGenerator = typing.AsyncGenerator -Text = typing.Text -TYPE_CHECKING = typing.TYPE_CHECKING - - -_PROTO_ALLOWLIST = { - 'collections.abc': [ - 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', - 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer', - ], - 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], - 'typing_extensions': ['Buffer'], -} - - -_EXCLUDED_ATTRS = { - "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol", - "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__", - "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__", - "__subclasshook__", "__orig_class__", "__init__", "__new__", - "__protocol_attrs__", "__callable_proto_members_only__", -} - -if sys.version_info < (3, 8): - _EXCLUDED_ATTRS |= { - "_gorg", "__next_in_mro__", "__extra__", "__tree_hash__", "__args__", - "__origin__" - } - -if sys.version_info >= (3, 9): - _EXCLUDED_ATTRS.add("__class_getitem__") - -if sys.version_info >= (3, 12): - _EXCLUDED_ATTRS.add("__type_params__") - -_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS) - - -def _get_protocol_attrs(cls): - attrs = set() - for base in cls.__mro__[:-1]: # without object - if base.__name__ in {'Protocol', 'Generic'}: - continue - annotations = getattr(base, '__annotations__', {}) - for attr in (*base.__dict__, *annotations): - if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): - attrs.add(attr) - return attrs - - -def _maybe_adjust_parameters(cls): - """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__. - - The contents of this function are very similar - to logic found in typing.Generic.__init_subclass__ - on the CPython main branch. - """ - tvars = [] - if '__orig_bases__' in cls.__dict__: - tvars = _collect_type_vars(cls.__orig_bases__) - # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn]. - # If found, tvars must be a subset of it. - # If not found, tvars is it. - # Also check for and reject plain Generic, - # and reject multiple Generic[...] and/or Protocol[...]. - gvars = None - for base in cls.__orig_bases__: - if (isinstance(base, typing._GenericAlias) and - base.__origin__ in (typing.Generic, Protocol)): - # for error messages - the_base = base.__origin__.__name__ - if gvars is not None: - raise TypeError( - "Cannot inherit from Generic[...]" - " and/or Protocol[...] multiple types.") - gvars = base.__parameters__ - if gvars is None: - gvars = tvars - else: - tvarset = set(tvars) - gvarset = set(gvars) - if not tvarset <= gvarset: - s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) - s_args = ', '.join(str(g) for g in gvars) - raise TypeError(f"Some type variables ({s_vars}) are" - f" not listed in {the_base}[{s_args}]") - tvars = gvars - cls.__parameters__ = tuple(tvars) - - -def _caller(depth=2): - try: - return sys._getframe(depth).f_globals.get('__name__', '__main__') - except (AttributeError, ValueError): # For platforms without _getframe() - return None - - -# The performance of runtime-checkable protocols is significantly improved on Python 3.12, -# so we backport the 3.12 version of Protocol to Python <=3.11 -if sys.version_info >= (3, 12): - Protocol = typing.Protocol -else: - def _allow_reckless_class_checks(depth=3): - """Allow instance and class checks for special stdlib modules. - The abc and functools modules indiscriminately call isinstance() and - issubclass() on the whole MRO of a user class, which may contain protocols. - """ - return _caller(depth) in {'abc', 'functools', None} - - def _no_init(self, *args, **kwargs): - if type(self)._is_protocol: - raise TypeError('Protocols cannot be instantiated') - - if sys.version_info >= (3, 8): - # Inheriting from typing._ProtocolMeta isn't actually desirable, - # but is necessary to allow typing.Protocol and typing_extensions.Protocol - # to mix without getting TypeErrors about "metaclass conflict" - _typing_Protocol = typing.Protocol - _ProtocolMetaBase = type(_typing_Protocol) - else: - _typing_Protocol = _marker - _ProtocolMetaBase = abc.ABCMeta - - class _ProtocolMeta(_ProtocolMetaBase): - # This metaclass is somewhat unfortunate, - # but is necessary for several reasons... - # - # NOTE: DO NOT call super() in any methods in this class - # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11 - # and those are slow - def __new__(mcls, name, bases, namespace, **kwargs): - if name == "Protocol" and len(bases) < 2: - pass - elif {Protocol, _typing_Protocol} & set(bases): - for base in bases: - if not ( - base in {object, typing.Generic, Protocol, _typing_Protocol} - or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) - or is_protocol(base) - ): - raise TypeError( - f"Protocols can only inherit from other protocols, " - f"got {base!r}" - ) - return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) - - def __init__(cls, *args, **kwargs): - abc.ABCMeta.__init__(cls, *args, **kwargs) - if getattr(cls, "_is_protocol", False): - cls.__protocol_attrs__ = _get_protocol_attrs(cls) - # PEP 544 prohibits using issubclass() - # with protocols that have non-method members. - cls.__callable_proto_members_only__ = all( - callable(getattr(cls, attr, None)) for attr in cls.__protocol_attrs__ - ) - - def __subclasscheck__(cls, other): - if cls is Protocol: - return type.__subclasscheck__(cls, other) - if ( - getattr(cls, '_is_protocol', False) - and not _allow_reckless_class_checks() - ): - if not isinstance(other, type): - # Same error message as for issubclass(1, int). - raise TypeError('issubclass() arg 1 must be a class') - if ( - not cls.__callable_proto_members_only__ - and cls.__dict__.get("__subclasshook__") is _proto_hook - ): - raise TypeError( - "Protocols with non-method members don't support issubclass()" - ) - if not getattr(cls, '_is_runtime_protocol', False): - raise TypeError( - "Instance and class checks can only be used with " - "@runtime_checkable protocols" - ) - return abc.ABCMeta.__subclasscheck__(cls, other) - - def __instancecheck__(cls, instance): - # We need this method for situations where attributes are - # assigned in __init__. - if cls is Protocol: - return type.__instancecheck__(cls, instance) - if not getattr(cls, "_is_protocol", False): - # i.e., it's a concrete subclass of a protocol - return abc.ABCMeta.__instancecheck__(cls, instance) - - if ( - not getattr(cls, '_is_runtime_protocol', False) and - not _allow_reckless_class_checks() - ): - raise TypeError("Instance and class checks can only be used with" - " @runtime_checkable protocols") - - if abc.ABCMeta.__instancecheck__(cls, instance): - return True - - for attr in cls.__protocol_attrs__: - try: - val = inspect.getattr_static(instance, attr) - except AttributeError: - break - if val is None and callable(getattr(cls, attr, None)): - break - else: - return True - - return False - - def __eq__(cls, other): - # Hack so that typing.Generic.__class_getitem__ - # treats typing_extensions.Protocol - # as equivalent to typing.Protocol on Python 3.8+ - if abc.ABCMeta.__eq__(cls, other) is True: - return True - return ( - cls is Protocol and other is getattr(typing, "Protocol", object()) - ) - - # This has to be defined, or the abc-module cache - # complains about classes with this metaclass being unhashable, - # if we define only __eq__! - def __hash__(cls) -> int: - return type.__hash__(cls) - - @classmethod - def _proto_hook(cls, other): - if not cls.__dict__.get('_is_protocol', False): - return NotImplemented - - for attr in cls.__protocol_attrs__: - for base in other.__mro__: - # Check if the members appears in the class dictionary... - if attr in base.__dict__: - if base.__dict__[attr] is None: - return NotImplemented - break - - # ...or in annotations, if it is a sub-protocol. - annotations = getattr(base, '__annotations__', {}) - if ( - isinstance(annotations, collections.abc.Mapping) - and attr in annotations - and is_protocol(other) - ): - break - else: - return NotImplemented - return True - - if sys.version_info >= (3, 8): - class Protocol(typing.Generic, metaclass=_ProtocolMeta): - __doc__ = typing.Protocol.__doc__ - __slots__ = () - _is_protocol = True - _is_runtime_protocol = False - - def __init_subclass__(cls, *args, **kwargs): - super().__init_subclass__(*args, **kwargs) - - # Determine if this is a protocol or a concrete subclass. - if not cls.__dict__.get('_is_protocol', False): - cls._is_protocol = any(b is Protocol for b in cls.__bases__) - - # Set (or override) the protocol subclass hook. - if '__subclasshook__' not in cls.__dict__: - cls.__subclasshook__ = _proto_hook - - # Prohibit instantiation for protocol classes - if cls._is_protocol and cls.__init__ is Protocol.__init__: - cls.__init__ = _no_init - - else: - class Protocol(metaclass=_ProtocolMeta): - # There is quite a lot of overlapping code with typing.Generic. - # Unfortunately it is hard to avoid this on Python <3.8, - # as the typing module on Python 3.7 doesn't let us subclass typing.Generic! - """Base class for protocol classes. Protocol classes are defined as:: - - class Proto(Protocol): - def meth(self) -> int: - ... - - Such classes are primarily used with static type checkers that recognize - structural subtyping (static duck-typing), for example:: - - class C: - def meth(self) -> int: - return 0 - - def func(x: Proto) -> int: - return x.meth() - - func(C()) # Passes static type check - - See PEP 544 for details. Protocol classes decorated with - @typing_extensions.runtime_checkable act - as simple-minded runtime-checkable protocols that check - only the presence of given attributes, ignoring their type signatures. - - Protocol classes can be generic, they are defined as:: - - class GenProto(Protocol[T]): - def meth(self) -> T: - ... - """ - __slots__ = () - _is_protocol = True - _is_runtime_protocol = False - - def __new__(cls, *args, **kwds): - if cls is Protocol: - raise TypeError("Type Protocol cannot be instantiated; " - "it can only be used as a base class") - return super().__new__(cls) - - @typing._tp_cache - def __class_getitem__(cls, params): - if not isinstance(params, tuple): - params = (params,) - if not params and cls is not typing.Tuple: - raise TypeError( - f"Parameter list to {cls.__qualname__}[...] cannot be empty") - msg = "Parameters to generic types must be types." - params = tuple(typing._type_check(p, msg) for p in params) - if cls is Protocol: - # Generic can only be subscripted with unique type variables. - if not all(isinstance(p, typing.TypeVar) for p in params): - i = 0 - while isinstance(params[i], typing.TypeVar): - i += 1 - raise TypeError( - "Parameters to Protocol[...] must all be type variables." - f" Parameter {i + 1} is {params[i]}") - if len(set(params)) != len(params): - raise TypeError( - "Parameters to Protocol[...] must all be unique") - else: - # Subscripting a regular Generic subclass. - _check_generic(cls, params, len(cls.__parameters__)) - return typing._GenericAlias(cls, params) - - def __init_subclass__(cls, *args, **kwargs): - if '__orig_bases__' in cls.__dict__: - error = typing.Generic in cls.__orig_bases__ - else: - error = typing.Generic in cls.__bases__ - if error: - raise TypeError("Cannot inherit from plain Generic") - _maybe_adjust_parameters(cls) - - # Determine if this is a protocol or a concrete subclass. - if not cls.__dict__.get('_is_protocol', None): - cls._is_protocol = any(b is Protocol for b in cls.__bases__) - - # Set (or override) the protocol subclass hook. - if '__subclasshook__' not in cls.__dict__: - cls.__subclasshook__ = _proto_hook - - # Prohibit instantiation for protocol classes - if cls._is_protocol and cls.__init__ is Protocol.__init__: - cls.__init__ = _no_init - - -if sys.version_info >= (3, 8): - runtime_checkable = typing.runtime_checkable -else: - def runtime_checkable(cls): - """Mark a protocol class as a runtime protocol, so that it - can be used with isinstance() and issubclass(). Raise TypeError - if applied to a non-protocol class. - - This allows a simple-minded structural check very similar to the - one-offs in collections.abc such as Hashable. - """ - if not ( - (isinstance(cls, _ProtocolMeta) or issubclass(cls, typing.Generic)) - and getattr(cls, "_is_protocol", False) - ): - raise TypeError('@runtime_checkable can be only applied to protocol classes,' - f' got {cls!r}') - cls._is_runtime_protocol = True - return cls - - -# Exists for backwards compatibility. -runtime = runtime_checkable - - -# Our version of runtime-checkable protocols is faster on Python 3.7-3.11 -if sys.version_info >= (3, 12): - SupportsInt = typing.SupportsInt - SupportsFloat = typing.SupportsFloat - SupportsComplex = typing.SupportsComplex - SupportsBytes = typing.SupportsBytes - SupportsIndex = typing.SupportsIndex - SupportsAbs = typing.SupportsAbs - SupportsRound = typing.SupportsRound -else: - @runtime_checkable - class SupportsInt(Protocol): - """An ABC with one abstract method __int__.""" - __slots__ = () - - @abc.abstractmethod - def __int__(self) -> int: - pass - - @runtime_checkable - class SupportsFloat(Protocol): - """An ABC with one abstract method __float__.""" - __slots__ = () - - @abc.abstractmethod - def __float__(self) -> float: - pass - - @runtime_checkable - class SupportsComplex(Protocol): - """An ABC with one abstract method __complex__.""" - __slots__ = () - - @abc.abstractmethod - def __complex__(self) -> complex: - pass - - @runtime_checkable - class SupportsBytes(Protocol): - """An ABC with one abstract method __bytes__.""" - __slots__ = () - - @abc.abstractmethod - def __bytes__(self) -> bytes: - pass - - @runtime_checkable - class SupportsIndex(Protocol): - __slots__ = () - - @abc.abstractmethod - def __index__(self) -> int: - pass - - @runtime_checkable - class SupportsAbs(Protocol[T_co]): - """ - An ABC with one abstract method __abs__ that is covariant in its return type. - """ - __slots__ = () - - @abc.abstractmethod - def __abs__(self) -> T_co: - pass - - @runtime_checkable - class SupportsRound(Protocol[T_co]): - """ - An ABC with one abstract method __round__ that is covariant in its return type. - """ - __slots__ = () - - @abc.abstractmethod - def __round__(self, ndigits: int = 0) -> T_co: - pass - - -def _ensure_subclassable(mro_entries): - def inner(func): - if sys.implementation.name == "pypy" and sys.version_info < (3, 9): - cls_dict = { - "__call__": staticmethod(func), - "__mro_entries__": staticmethod(mro_entries) - } - t = type(func.__name__, (), cls_dict) - return functools.update_wrapper(t(), func) - else: - func.__mro_entries__ = mro_entries - return func - return inner - - -if sys.version_info >= (3, 13): - # The standard library TypedDict in Python 3.8 does not store runtime information - # about which (if any) keys are optional. See https://bugs.python.org/issue38834 - # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" - # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 - # The standard library TypedDict below Python 3.11 does not store runtime - # information about optional and required keys when using Required or NotRequired. - # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. - # Aaaand on 3.12 we add __orig_bases__ to TypedDict - # to enable better runtime introspection. - # On 3.13 we deprecate some odd ways of creating TypedDicts. - TypedDict = typing.TypedDict - _TypedDictMeta = typing._TypedDictMeta - is_typeddict = typing.is_typeddict -else: - # 3.10.0 and later - _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters - - if sys.version_info >= (3, 8): - _fake_name = "Protocol" - else: - _fake_name = "_Protocol" - - class _TypedDictMeta(type): - def __new__(cls, name, bases, ns, total=True): - """Create new typed dict class object. - - This method is called when TypedDict is subclassed, - or when TypedDict is instantiated. This way - TypedDict supports all three syntax forms described in its docstring. - Subclasses and instances of TypedDict return actual dictionaries. - """ - for base in bases: - if type(base) is not _TypedDictMeta and base is not typing.Generic: - raise TypeError('cannot inherit from both a TypedDict type ' - 'and a non-TypedDict base class') - - if any(issubclass(b, typing.Generic) for b in bases): - generic_base = (typing.Generic,) - else: - generic_base = () - - # typing.py generally doesn't let you inherit from plain Generic, unless - # the name of the class happens to be "Protocol" (or "_Protocol" on 3.7). - tp_dict = type.__new__(_TypedDictMeta, _fake_name, (*generic_base, dict), ns) - tp_dict.__name__ = name - if tp_dict.__qualname__ == _fake_name: - tp_dict.__qualname__ = name - - if not hasattr(tp_dict, '__orig_bases__'): - tp_dict.__orig_bases__ = bases - - annotations = {} - own_annotations = ns.get('__annotations__', {}) - msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" - if _TAKES_MODULE: - own_annotations = { - n: typing._type_check(tp, msg, module=tp_dict.__module__) - for n, tp in own_annotations.items() - } - else: - own_annotations = { - n: typing._type_check(tp, msg) - for n, tp in own_annotations.items() - } - required_keys = set() - optional_keys = set() - - for base in bases: - annotations.update(base.__dict__.get('__annotations__', {})) - required_keys.update(base.__dict__.get('__required_keys__', ())) - optional_keys.update(base.__dict__.get('__optional_keys__', ())) - - annotations.update(own_annotations) - for annotation_key, annotation_type in own_annotations.items(): - annotation_origin = get_origin(annotation_type) - if annotation_origin is Annotated: - annotation_args = get_args(annotation_type) - if annotation_args: - annotation_type = annotation_args[0] - annotation_origin = get_origin(annotation_type) - - if annotation_origin is Required: - required_keys.add(annotation_key) - elif annotation_origin is NotRequired: - optional_keys.add(annotation_key) - elif total: - required_keys.add(annotation_key) - else: - optional_keys.add(annotation_key) - - tp_dict.__annotations__ = annotations - tp_dict.__required_keys__ = frozenset(required_keys) - tp_dict.__optional_keys__ = frozenset(optional_keys) - if not hasattr(tp_dict, '__total__'): - tp_dict.__total__ = total - return tp_dict - - __call__ = dict # static method - - def __subclasscheck__(cls, other): - # Typed dicts are only for static structural subtyping. - raise TypeError('TypedDict does not support instance and class checks') - - __instancecheck__ = __subclasscheck__ - - _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) - - @_ensure_subclassable(lambda bases: (_TypedDict,)) - def TypedDict(__typename, __fields=_marker, *, total=True, **kwargs): - """A simple typed namespace. At runtime it is equivalent to a plain dict. - - TypedDict creates a dictionary type such that a type checker will expect all - instances to have a certain set of keys, where each key is - associated with a value of a consistent type. This expectation - is not checked at runtime. - - Usage:: - - class Point2D(TypedDict): - x: int - y: int - label: str - - a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK - b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check - - assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') - - The type info can be accessed via the Point2D.__annotations__ dict, and - the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. - TypedDict supports an additional equivalent form:: - - Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) - - By default, all keys must be present in a TypedDict. It is possible - to override this by specifying totality:: - - class Point2D(TypedDict, total=False): - x: int - y: int - - This means that a Point2D TypedDict can have any of the keys omitted. A type - checker is only expected to support a literal False or True as the value of - the total argument. True is the default, and makes all items defined in the - class body be required. - - The Required and NotRequired special forms can also be used to mark - individual keys as being required or not required:: - - class Point2D(TypedDict): - x: int # the "x" key must always be present (Required is the default) - y: NotRequired[int] # the "y" key can be omitted - - See PEP 655 for more details on Required and NotRequired. - """ - if __fields is _marker or __fields is None: - if __fields is _marker: - deprecated_thing = "Failing to pass a value for the 'fields' parameter" - else: - deprecated_thing = "Passing `None` as the 'fields' parameter" - - example = f"`{__typename} = TypedDict({__typename!r}, {{}})`" - deprecation_msg = ( - f"{deprecated_thing} is deprecated and will be disallowed in " - "Python 3.15. To create a TypedDict class with 0 fields " - "using the functional syntax, pass an empty dictionary, e.g. " - ) + example + "." - warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) - __fields = kwargs - elif kwargs: - raise TypeError("TypedDict takes either a dict or keyword arguments," - " but not both") - if kwargs: - warnings.warn( - "The kwargs-based syntax for TypedDict definitions is deprecated " - "in Python 3.11, will be removed in Python 3.13, and may not be " - "understood by third-party type checkers.", - DeprecationWarning, - stacklevel=2, - ) - - ns = {'__annotations__': dict(__fields)} - module = _caller() - if module is not None: - # Setting correct module is necessary to make typed dict classes pickleable. - ns['__module__'] = module - - td = _TypedDictMeta(__typename, (), ns, total=total) - td.__orig_bases__ = (TypedDict,) - return td - - if hasattr(typing, "_TypedDictMeta"): - _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) - else: - _TYPEDDICT_TYPES = (_TypedDictMeta,) - - def is_typeddict(tp): - """Check if an annotation is a TypedDict class - - For example:: - class Film(TypedDict): - title: str - year: int - - is_typeddict(Film) # => True - is_typeddict(Union[list, str]) # => False - """ - # On 3.8, this would otherwise return True - if hasattr(typing, "TypedDict") and tp is typing.TypedDict: - return False - return isinstance(tp, _TYPEDDICT_TYPES) - - -if hasattr(typing, "assert_type"): - assert_type = typing.assert_type - -else: - def assert_type(__val, __typ): - """Assert (to the type checker) that the value is of the given type. - - When the type checker encounters a call to assert_type(), it - emits an error if the value is not of the specified type:: - - def greet(name: str) -> None: - assert_type(name, str) # ok - assert_type(name, int) # type checker error - - At runtime this returns the first argument unchanged and otherwise - does nothing. - """ - return __val - - -if hasattr(typing, "Required"): - get_type_hints = typing.get_type_hints -else: - # replaces _strip_annotations() - def _strip_extras(t): - """Strips Annotated, Required and NotRequired from a given type.""" - if isinstance(t, _AnnotatedAlias): - return _strip_extras(t.__origin__) - if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired): - return _strip_extras(t.__args__[0]) - if isinstance(t, typing._GenericAlias): - stripped_args = tuple(_strip_extras(a) for a in t.__args__) - if stripped_args == t.__args__: - return t - return t.copy_with(stripped_args) - if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): - stripped_args = tuple(_strip_extras(a) for a in t.__args__) - if stripped_args == t.__args__: - return t - return _types.GenericAlias(t.__origin__, stripped_args) - if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): - stripped_args = tuple(_strip_extras(a) for a in t.__args__) - if stripped_args == t.__args__: - return t - return functools.reduce(operator.or_, stripped_args) - - return t - - def get_type_hints(obj, globalns=None, localns=None, include_extras=False): - """Return type hints for an object. - - This is often the same as obj.__annotations__, but it handles - forward references encoded as string literals, adds Optional[t] if a - default value equal to None is set and recursively replaces all - 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' - (unless 'include_extras=True'). - - The argument may be a module, class, method, or function. The annotations - are returned as a dictionary. For classes, annotations include also - inherited members. - - TypeError is raised if the argument is not of a type that can contain - annotations, and an empty dictionary is returned if no annotations are - present. - - BEWARE -- the behavior of globalns and localns is counterintuitive - (unless you are familiar with how eval() and exec() work). The - search order is locals first, then globals. - - - If no dict arguments are passed, an attempt is made to use the - globals from obj (or the respective module's globals for classes), - and these are also used as the locals. If the object does not appear - to have globals, an empty dictionary is used. - - - If one dict argument is passed, it is used for both globals and - locals. - - - If two dict arguments are passed, they specify globals and - locals, respectively. - """ - if hasattr(typing, "Annotated"): - hint = typing.get_type_hints( - obj, globalns=globalns, localns=localns, include_extras=True - ) - else: - hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) - if include_extras: - return hint - return {k: _strip_extras(t) for k, t in hint.items()} - - -# Python 3.9+ has PEP 593 (Annotated) -if hasattr(typing, 'Annotated'): - Annotated = typing.Annotated - # Not exported and not a public API, but needed for get_origin() and get_args() - # to work. - _AnnotatedAlias = typing._AnnotatedAlias -# 3.7-3.8 -else: - class _AnnotatedAlias(typing._GenericAlias, _root=True): - """Runtime representation of an annotated type. - - At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' - with extra annotations. The alias behaves like a normal typing alias, - instantiating is the same as instantiating the underlying type, binding - it to types is also the same. - """ - def __init__(self, origin, metadata): - if isinstance(origin, _AnnotatedAlias): - metadata = origin.__metadata__ + metadata - origin = origin.__origin__ - super().__init__(origin, origin) - self.__metadata__ = metadata - - def copy_with(self, params): - assert len(params) == 1 - new_type = params[0] - return _AnnotatedAlias(new_type, self.__metadata__) - - def __repr__(self): - return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, " - f"{', '.join(repr(a) for a in self.__metadata__)}]") - - def __reduce__(self): - return operator.getitem, ( - Annotated, (self.__origin__,) + self.__metadata__ - ) - - def __eq__(self, other): - if not isinstance(other, _AnnotatedAlias): - return NotImplemented - if self.__origin__ != other.__origin__: - return False - return self.__metadata__ == other.__metadata__ - - def __hash__(self): - return hash((self.__origin__, self.__metadata__)) - - class Annotated: - """Add context specific metadata to a type. - - Example: Annotated[int, runtime_check.Unsigned] indicates to the - hypothetical runtime_check module that this type is an unsigned int. - Every other consumer of this type can ignore this metadata and treat - this type as int. - - The first argument to Annotated must be a valid type (and will be in - the __origin__ field), the remaining arguments are kept as a tuple in - the __extra__ field. - - Details: - - - It's an error to call `Annotated` with less than two arguments. - - Nested Annotated are flattened:: - - Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - - - Instantiating an annotated type is equivalent to instantiating the - underlying type:: - - Annotated[C, Ann1](5) == C(5) - - - Annotated can be used as a generic type alias:: - - Optimized = Annotated[T, runtime.Optimize()] - Optimized[int] == Annotated[int, runtime.Optimize()] - - OptimizedList = Annotated[List[T], runtime.Optimize()] - OptimizedList[int] == Annotated[List[int], runtime.Optimize()] - """ - - __slots__ = () - - def __new__(cls, *args, **kwargs): - raise TypeError("Type Annotated cannot be instantiated.") - - @typing._tp_cache - def __class_getitem__(cls, params): - if not isinstance(params, tuple) or len(params) < 2: - raise TypeError("Annotated[...] should be used " - "with at least two arguments (a type and an " - "annotation).") - allowed_special_forms = (ClassVar, Final) - if get_origin(params[0]) in allowed_special_forms: - origin = params[0] - else: - msg = "Annotated[t, ...]: t must be a type." - origin = typing._type_check(params[0], msg) - metadata = tuple(params[1:]) - return _AnnotatedAlias(origin, metadata) - - def __init_subclass__(cls, *args, **kwargs): - raise TypeError( - f"Cannot subclass {cls.__module__}.Annotated" - ) - -# Python 3.8 has get_origin() and get_args() but those implementations aren't -# Annotated-aware, so we can't use those. Python 3.9's versions don't support -# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. -if sys.version_info[:2] >= (3, 10): - get_origin = typing.get_origin - get_args = typing.get_args -# 3.7-3.9 -else: - try: - # 3.9+ - from typing import _BaseGenericAlias - except ImportError: - _BaseGenericAlias = typing._GenericAlias - try: - # 3.9+ - from typing import GenericAlias as _typing_GenericAlias - except ImportError: - _typing_GenericAlias = typing._GenericAlias - - def get_origin(tp): - """Get the unsubscripted version of a type. - - This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar - and Annotated. Return None for unsupported types. Examples:: - - get_origin(Literal[42]) is Literal - get_origin(int) is None - get_origin(ClassVar[int]) is ClassVar - get_origin(Generic) is Generic - get_origin(Generic[T]) is Generic - get_origin(Union[T, int]) is Union - get_origin(List[Tuple[T, T]][int]) == list - get_origin(P.args) is P - """ - if isinstance(tp, _AnnotatedAlias): - return Annotated - if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias, - ParamSpecArgs, ParamSpecKwargs)): - return tp.__origin__ - if tp is typing.Generic: - return typing.Generic - return None - - def get_args(tp): - """Get type arguments with all substitutions performed. - - For unions, basic simplifications used by Union constructor are performed. - Examples:: - get_args(Dict[str, int]) == (str, int) - get_args(int) == () - get_args(Union[int, Union[T, int], str][int]) == (int, str) - get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) - get_args(Callable[[], T][int]) == ([], int) - """ - if isinstance(tp, _AnnotatedAlias): - return (tp.__origin__,) + tp.__metadata__ - if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)): - if getattr(tp, "_special", False): - return () - res = tp.__args__ - if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: - res = (list(res[:-1]), res[-1]) - return res - return () - - -# 3.10+ -if hasattr(typing, 'TypeAlias'): - TypeAlias = typing.TypeAlias -# 3.9 -elif sys.version_info[:2] >= (3, 9): - @_ExtensionsSpecialForm - def TypeAlias(self, parameters): - """Special marker indicating that an assignment should - be recognized as a proper type alias definition by type - checkers. - - For example:: - - Predicate: TypeAlias = Callable[..., bool] - - It's invalid when used anywhere except as in the example above. - """ - raise TypeError(f"{self} is not subscriptable") -# 3.7-3.8 -else: - TypeAlias = _ExtensionsSpecialForm( - 'TypeAlias', - doc="""Special marker indicating that an assignment should - be recognized as a proper type alias definition by type - checkers. - - For example:: - - Predicate: TypeAlias = Callable[..., bool] - - It's invalid when used anywhere except as in the example - above.""" - ) - - -def _set_default(type_param, default): - if isinstance(default, (tuple, list)): - type_param.__default__ = tuple((typing._type_check(d, "Default must be a type") - for d in default)) - elif default != _marker: - type_param.__default__ = typing._type_check(default, "Default must be a type") - else: - type_param.__default__ = None - - -def _set_module(typevarlike): - # for pickling: - def_mod = _caller(depth=3) - if def_mod != 'typing_extensions': - typevarlike.__module__ = def_mod - - -class _DefaultMixin: - """Mixin for TypeVarLike defaults.""" - - __slots__ = () - __init__ = _set_default - - -# Classes using this metaclass must provide a _backported_typevarlike ClassVar -class _TypeVarLikeMeta(type): - def __instancecheck__(cls, __instance: Any) -> bool: - return isinstance(__instance, cls._backported_typevarlike) - - -# Add default and infer_variance parameters from PEP 696 and 695 -class TypeVar(metaclass=_TypeVarLikeMeta): - """Type variable.""" - - _backported_typevarlike = typing.TypeVar - - def __new__(cls, name, *constraints, bound=None, - covariant=False, contravariant=False, - default=_marker, infer_variance=False): - if hasattr(typing, "TypeAliasType"): - # PEP 695 implemented, can pass infer_variance to typing.TypeVar - typevar = typing.TypeVar(name, *constraints, bound=bound, - covariant=covariant, contravariant=contravariant, - infer_variance=infer_variance) - else: - typevar = typing.TypeVar(name, *constraints, bound=bound, - covariant=covariant, contravariant=contravariant) - if infer_variance and (covariant or contravariant): - raise ValueError("Variance cannot be specified with infer_variance.") - typevar.__infer_variance__ = infer_variance - _set_default(typevar, default) - _set_module(typevar) - return typevar - - def __init_subclass__(cls) -> None: - raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") - - -# Python 3.10+ has PEP 612 -if hasattr(typing, 'ParamSpecArgs'): - ParamSpecArgs = typing.ParamSpecArgs - ParamSpecKwargs = typing.ParamSpecKwargs -# 3.7-3.9 -else: - class _Immutable: - """Mixin to indicate that object should not be copied.""" - __slots__ = () - - def __copy__(self): - return self - - def __deepcopy__(self, memo): - return self - - class ParamSpecArgs(_Immutable): - """The args for a ParamSpec object. - - Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. - - ParamSpecArgs objects have a reference back to their ParamSpec: - - P.args.__origin__ is P - - This type is meant for runtime introspection and has no special meaning to - static type checkers. - """ - def __init__(self, origin): - self.__origin__ = origin - - def __repr__(self): - return f"{self.__origin__.__name__}.args" - - def __eq__(self, other): - if not isinstance(other, ParamSpecArgs): - return NotImplemented - return self.__origin__ == other.__origin__ - - class ParamSpecKwargs(_Immutable): - """The kwargs for a ParamSpec object. - - Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. - - ParamSpecKwargs objects have a reference back to their ParamSpec: - - P.kwargs.__origin__ is P - - This type is meant for runtime introspection and has no special meaning to - static type checkers. - """ - def __init__(self, origin): - self.__origin__ = origin - - def __repr__(self): - return f"{self.__origin__.__name__}.kwargs" - - def __eq__(self, other): - if not isinstance(other, ParamSpecKwargs): - return NotImplemented - return self.__origin__ == other.__origin__ - -# 3.10+ -if hasattr(typing, 'ParamSpec'): - - # Add default parameter - PEP 696 - class ParamSpec(metaclass=_TypeVarLikeMeta): - """Parameter specification.""" - - _backported_typevarlike = typing.ParamSpec - - def __new__(cls, name, *, bound=None, - covariant=False, contravariant=False, - infer_variance=False, default=_marker): - if hasattr(typing, "TypeAliasType"): - # PEP 695 implemented, can pass infer_variance to typing.TypeVar - paramspec = typing.ParamSpec(name, bound=bound, - covariant=covariant, - contravariant=contravariant, - infer_variance=infer_variance) - else: - paramspec = typing.ParamSpec(name, bound=bound, - covariant=covariant, - contravariant=contravariant) - paramspec.__infer_variance__ = infer_variance - - _set_default(paramspec, default) - _set_module(paramspec) - return paramspec - - def __init_subclass__(cls) -> None: - raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") - -# 3.7-3.9 -else: - - # Inherits from list as a workaround for Callable checks in Python < 3.9.2. - class ParamSpec(list, _DefaultMixin): - """Parameter specification variable. - - Usage:: - - P = ParamSpec('P') - - Parameter specification variables exist primarily for the benefit of static - type checkers. They are used to forward the parameter types of one - callable to another callable, a pattern commonly found in higher order - functions and decorators. They are only valid when used in ``Concatenate``, - or s the first argument to ``Callable``. In Python 3.10 and higher, - they are also supported in user-defined Generics at runtime. - See class Generic for more information on generic types. An - example for annotating a decorator:: - - T = TypeVar('T') - P = ParamSpec('P') - - def add_logging(f: Callable[P, T]) -> Callable[P, T]: - '''A type-safe decorator to add logging to a function.''' - def inner(*args: P.args, **kwargs: P.kwargs) -> T: - logging.info(f'{f.__name__} was called') - return f(*args, **kwargs) - return inner - - @add_logging - def add_two(x: float, y: float) -> float: - '''Add two numbers together.''' - return x + y - - Parameter specification variables defined with covariant=True or - contravariant=True can be used to declare covariant or contravariant - generic types. These keyword arguments are valid, but their actual semantics - are yet to be decided. See PEP 612 for details. - - Parameter specification variables can be introspected. e.g.: - - P.__name__ == 'T' - P.__bound__ == None - P.__covariant__ == False - P.__contravariant__ == False - - Note that only parameter specification variables defined in global scope can - be pickled. - """ - - # Trick Generic __parameters__. - __class__ = typing.TypeVar - - @property - def args(self): - return ParamSpecArgs(self) - - @property - def kwargs(self): - return ParamSpecKwargs(self) - - def __init__(self, name, *, bound=None, covariant=False, contravariant=False, - infer_variance=False, default=_marker): - super().__init__([self]) - self.__name__ = name - self.__covariant__ = bool(covariant) - self.__contravariant__ = bool(contravariant) - self.__infer_variance__ = bool(infer_variance) - if bound: - self.__bound__ = typing._type_check(bound, 'Bound must be a type.') - else: - self.__bound__ = None - _DefaultMixin.__init__(self, default) - - # for pickling: - def_mod = _caller() - if def_mod != 'typing_extensions': - self.__module__ = def_mod - - def __repr__(self): - if self.__infer_variance__: - prefix = '' - elif self.__covariant__: - prefix = '+' - elif self.__contravariant__: - prefix = '-' - else: - prefix = '~' - return prefix + self.__name__ - - def __hash__(self): - return object.__hash__(self) - - def __eq__(self, other): - return self is other - - def __reduce__(self): - return self.__name__ - - # Hack to get typing._type_check to pass. - def __call__(self, *args, **kwargs): - pass - - -# 3.7-3.9 -if not hasattr(typing, 'Concatenate'): - # Inherits from list as a workaround for Callable checks in Python < 3.9.2. - class _ConcatenateGenericAlias(list): - - # Trick Generic into looking into this for __parameters__. - __class__ = typing._GenericAlias - - # Flag in 3.8. - _special = False - - def __init__(self, origin, args): - super().__init__(args) - self.__origin__ = origin - self.__args__ = args - - def __repr__(self): - _type_repr = typing._type_repr - return (f'{_type_repr(self.__origin__)}' - f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') - - def __hash__(self): - return hash((self.__origin__, self.__args__)) - - # Hack to get typing._type_check to pass in Generic. - def __call__(self, *args, **kwargs): - pass - - @property - def __parameters__(self): - return tuple( - tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) - ) - - -# 3.7-3.9 -@typing._tp_cache -def _concatenate_getitem(self, parameters): - if parameters == (): - raise TypeError("Cannot take a Concatenate of no types.") - if not isinstance(parameters, tuple): - parameters = (parameters,) - if not isinstance(parameters[-1], ParamSpec): - raise TypeError("The last parameter to Concatenate should be a " - "ParamSpec variable.") - msg = "Concatenate[arg, ...]: each arg must be a type." - parameters = tuple(typing._type_check(p, msg) for p in parameters) - return _ConcatenateGenericAlias(self, parameters) - - -# 3.10+ -if hasattr(typing, 'Concatenate'): - Concatenate = typing.Concatenate - _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811 -# 3.9 -elif sys.version_info[:2] >= (3, 9): - @_ExtensionsSpecialForm - def Concatenate(self, parameters): - """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a - higher order function which adds, removes or transforms parameters of a - callable. - - For example:: - - Callable[Concatenate[int, P], int] - - See PEP 612 for detailed information. - """ - return _concatenate_getitem(self, parameters) -# 3.7-8 -else: - class _ConcatenateForm(_ExtensionsSpecialForm, _root=True): - def __getitem__(self, parameters): - return _concatenate_getitem(self, parameters) - - Concatenate = _ConcatenateForm( - 'Concatenate', - doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a - higher order function which adds, removes or transforms parameters of a - callable. - - For example:: - - Callable[Concatenate[int, P], int] - - See PEP 612 for detailed information. - """) - -# 3.10+ -if hasattr(typing, 'TypeGuard'): - TypeGuard = typing.TypeGuard -# 3.9 -elif sys.version_info[:2] >= (3, 9): - @_ExtensionsSpecialForm - def TypeGuard(self, parameters): - """Special typing form used to annotate the return type of a user-defined - type guard function. ``TypeGuard`` only accepts a single type argument. - At runtime, functions marked this way should return a boolean. - - ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static - type checkers to determine a more precise type of an expression within a - program's code flow. Usually type narrowing is done by analyzing - conditional code flow and applying the narrowing to a block of code. The - conditional expression here is sometimes referred to as a "type guard". - - Sometimes it would be convenient to use a user-defined boolean function - as a type guard. Such a function should use ``TypeGuard[...]`` as its - return type to alert static type checkers to this intention. - - Using ``-> TypeGuard`` tells the static type checker that for a given - function: - - 1. The return value is a boolean. - 2. If the return value is ``True``, the type of its argument - is the type inside ``TypeGuard``. - - For example:: - - def is_str(val: Union[str, float]): - # "isinstance" type guard - if isinstance(val, str): - # Type of ``val`` is narrowed to ``str`` - ... - else: - # Else, type of ``val`` is narrowed to ``float``. - ... - - Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower - form of ``TypeA`` (it can even be a wider form) and this may lead to - type-unsafe results. The main reason is to allow for things like - narrowing ``List[object]`` to ``List[str]`` even though the latter is not - a subtype of the former, since ``List`` is invariant. The responsibility of - writing type-safe type guards is left to the user. - - ``TypeGuard`` also works with type variables. For more information, see - PEP 647 (User-Defined Type Guards). - """ - item = typing._type_check(parameters, f'{self} accepts only a single type.') - return typing._GenericAlias(self, (item,)) -# 3.7-3.8 -else: - class _TypeGuardForm(_ExtensionsSpecialForm, _root=True): - def __getitem__(self, parameters): - item = typing._type_check(parameters, - f'{self._name} accepts only a single type') - return typing._GenericAlias(self, (item,)) - - TypeGuard = _TypeGuardForm( - 'TypeGuard', - doc="""Special typing form used to annotate the return type of a user-defined - type guard function. ``TypeGuard`` only accepts a single type argument. - At runtime, functions marked this way should return a boolean. - - ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static - type checkers to determine a more precise type of an expression within a - program's code flow. Usually type narrowing is done by analyzing - conditional code flow and applying the narrowing to a block of code. The - conditional expression here is sometimes referred to as a "type guard". - - Sometimes it would be convenient to use a user-defined boolean function - as a type guard. Such a function should use ``TypeGuard[...]`` as its - return type to alert static type checkers to this intention. - - Using ``-> TypeGuard`` tells the static type checker that for a given - function: - - 1. The return value is a boolean. - 2. If the return value is ``True``, the type of its argument - is the type inside ``TypeGuard``. - - For example:: - - def is_str(val: Union[str, float]): - # "isinstance" type guard - if isinstance(val, str): - # Type of ``val`` is narrowed to ``str`` - ... - else: - # Else, type of ``val`` is narrowed to ``float``. - ... - - Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower - form of ``TypeA`` (it can even be a wider form) and this may lead to - type-unsafe results. The main reason is to allow for things like - narrowing ``List[object]`` to ``List[str]`` even though the latter is not - a subtype of the former, since ``List`` is invariant. The responsibility of - writing type-safe type guards is left to the user. - - ``TypeGuard`` also works with type variables. For more information, see - PEP 647 (User-Defined Type Guards). - """) - - -# Vendored from cpython typing._SpecialFrom -class _SpecialForm(typing._Final, _root=True): - __slots__ = ('_name', '__doc__', '_getitem') - - def __init__(self, getitem): - self._getitem = getitem - self._name = getitem.__name__ - self.__doc__ = getitem.__doc__ - - def __getattr__(self, item): - if item in {'__name__', '__qualname__'}: - return self._name - - raise AttributeError(item) - - def __mro_entries__(self, bases): - raise TypeError(f"Cannot subclass {self!r}") - - def __repr__(self): - return f'typing_extensions.{self._name}' - - def __reduce__(self): - return self._name - - def __call__(self, *args, **kwds): - raise TypeError(f"Cannot instantiate {self!r}") - - def __or__(self, other): - return typing.Union[self, other] - - def __ror__(self, other): - return typing.Union[other, self] - - def __instancecheck__(self, obj): - raise TypeError(f"{self} cannot be used with isinstance()") - - def __subclasscheck__(self, cls): - raise TypeError(f"{self} cannot be used with issubclass()") - - @typing._tp_cache - def __getitem__(self, parameters): - return self._getitem(self, parameters) - - -if hasattr(typing, "LiteralString"): - LiteralString = typing.LiteralString -else: - @_SpecialForm - def LiteralString(self, params): - """Represents an arbitrary literal string. - - Example:: - - from pip._vendor.typing_extensions import LiteralString - - def query(sql: LiteralString) -> ...: - ... - - query("SELECT * FROM table") # ok - query(f"SELECT * FROM {input()}") # not ok - - See PEP 675 for details. - - """ - raise TypeError(f"{self} is not subscriptable") - - -if hasattr(typing, "Self"): - Self = typing.Self -else: - @_SpecialForm - def Self(self, params): - """Used to spell the type of "self" in classes. - - Example:: - - from typing import Self - - class ReturnsSelf: - def parse(self, data: bytes) -> Self: - ... - return self - - """ - - raise TypeError(f"{self} is not subscriptable") - - -if hasattr(typing, "Never"): - Never = typing.Never -else: - @_SpecialForm - def Never(self, params): - """The bottom type, a type that has no members. - - This can be used to define a function that should never be - called, or a function that never returns:: - - from pip._vendor.typing_extensions import Never - - def never_call_me(arg: Never) -> None: - pass - - def int_or_str(arg: int | str) -> None: - never_call_me(arg) # type checker error - match arg: - case int(): - print("It's an int") - case str(): - print("It's a str") - case _: - never_call_me(arg) # ok, arg is of type Never - - """ - - raise TypeError(f"{self} is not subscriptable") - - -if hasattr(typing, 'Required'): - Required = typing.Required - NotRequired = typing.NotRequired -elif sys.version_info[:2] >= (3, 9): - @_ExtensionsSpecialForm - def Required(self, parameters): - """A special typing construct to mark a key of a total=False TypedDict - as required. For example: - - class Movie(TypedDict, total=False): - title: Required[str] - year: int - - m = Movie( - title='The Matrix', # typechecker error if key is omitted - year=1999, - ) - - There is no runtime checking that a required key is actually provided - when instantiating a related TypedDict. - """ - item = typing._type_check(parameters, f'{self._name} accepts only a single type.') - return typing._GenericAlias(self, (item,)) - - @_ExtensionsSpecialForm - def NotRequired(self, parameters): - """A special typing construct to mark a key of a TypedDict as - potentially missing. For example: - - class Movie(TypedDict): - title: str - year: NotRequired[int] - - m = Movie( - title='The Matrix', # typechecker error if key is omitted - year=1999, - ) - """ - item = typing._type_check(parameters, f'{self._name} accepts only a single type.') - return typing._GenericAlias(self, (item,)) - -else: - class _RequiredForm(_ExtensionsSpecialForm, _root=True): - def __getitem__(self, parameters): - item = typing._type_check(parameters, - f'{self._name} accepts only a single type.') - return typing._GenericAlias(self, (item,)) - - Required = _RequiredForm( - 'Required', - doc="""A special typing construct to mark a key of a total=False TypedDict - as required. For example: - - class Movie(TypedDict, total=False): - title: Required[str] - year: int - - m = Movie( - title='The Matrix', # typechecker error if key is omitted - year=1999, - ) - - There is no runtime checking that a required key is actually provided - when instantiating a related TypedDict. - """) - NotRequired = _RequiredForm( - 'NotRequired', - doc="""A special typing construct to mark a key of a TypedDict as - potentially missing. For example: - - class Movie(TypedDict): - title: str - year: NotRequired[int] - - m = Movie( - title='The Matrix', # typechecker error if key is omitted - year=1999, - ) - """) - - -_UNPACK_DOC = """\ -Type unpack operator. - -The type unpack operator takes the child types from some container type, -such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For -example: - - # For some generic class `Foo`: - Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] - - Ts = TypeVarTuple('Ts') - # Specifies that `Bar` is generic in an arbitrary number of types. - # (Think of `Ts` as a tuple of an arbitrary number of individual - # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the - # `Generic[]`.) - class Bar(Generic[Unpack[Ts]]): ... - Bar[int] # Valid - Bar[int, str] # Also valid - -From Python 3.11, this can also be done using the `*` operator: - - Foo[*tuple[int, str]] - class Bar(Generic[*Ts]): ... - -The operator can also be used along with a `TypedDict` to annotate -`**kwargs` in a function signature. For instance: - - class Movie(TypedDict): - name: str - year: int - - # This function expects two keyword arguments - *name* of type `str` and - # *year* of type `int`. - def foo(**kwargs: Unpack[Movie]): ... - -Note that there is only some runtime checking of this operator. Not -everything the runtime allows may be accepted by static type checkers. - -For more information, see PEP 646 and PEP 692. -""" - - -if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[] - Unpack = typing.Unpack - - def _is_unpack(obj): - return get_origin(obj) is Unpack - -elif sys.version_info[:2] >= (3, 9): - class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): - def __init__(self, getitem): - super().__init__(getitem) - self.__doc__ = _UNPACK_DOC - - class _UnpackAlias(typing._GenericAlias, _root=True): - __class__ = typing.TypeVar - - @_UnpackSpecialForm - def Unpack(self, parameters): - item = typing._type_check(parameters, f'{self._name} accepts only a single type.') - return _UnpackAlias(self, (item,)) - - def _is_unpack(obj): - return isinstance(obj, _UnpackAlias) - -else: - class _UnpackAlias(typing._GenericAlias, _root=True): - __class__ = typing.TypeVar - - class _UnpackForm(_ExtensionsSpecialForm, _root=True): - def __getitem__(self, parameters): - item = typing._type_check(parameters, - f'{self._name} accepts only a single type.') - return _UnpackAlias(self, (item,)) - - Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC) - - def _is_unpack(obj): - return isinstance(obj, _UnpackAlias) - - -if hasattr(typing, "TypeVarTuple"): # 3.11+ - - # Add default parameter - PEP 696 - class TypeVarTuple(metaclass=_TypeVarLikeMeta): - """Type variable tuple.""" - - _backported_typevarlike = typing.TypeVarTuple - - def __new__(cls, name, *, default=_marker): - tvt = typing.TypeVarTuple(name) - _set_default(tvt, default) - _set_module(tvt) - return tvt - - def __init_subclass__(self, *args, **kwds): - raise TypeError("Cannot subclass special typing classes") - -else: - class TypeVarTuple(_DefaultMixin): - """Type variable tuple. - - Usage:: - - Ts = TypeVarTuple('Ts') - - In the same way that a normal type variable is a stand-in for a single - type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* - type such as ``Tuple[int, str]``. - - Type variable tuples can be used in ``Generic`` declarations. - Consider the following example:: - - class Array(Generic[*Ts]): ... - - The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, - where ``T1`` and ``T2`` are type variables. To use these type variables - as type parameters of ``Array``, we must *unpack* the type variable tuple using - the star operator: ``*Ts``. The signature of ``Array`` then behaves - as if we had simply written ``class Array(Generic[T1, T2]): ...``. - In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows - us to parameterise the class with an *arbitrary* number of type parameters. - - Type variable tuples can be used anywhere a normal ``TypeVar`` can. - This includes class definitions, as shown above, as well as function - signatures and variable annotations:: - - class Array(Generic[*Ts]): - - def __init__(self, shape: Tuple[*Ts]): - self._shape: Tuple[*Ts] = shape - - def get_shape(self) -> Tuple[*Ts]: - return self._shape - - shape = (Height(480), Width(640)) - x: Array[Height, Width] = Array(shape) - y = abs(x) # Inferred type is Array[Height, Width] - z = x + x # ... is Array[Height, Width] - x.get_shape() # ... is tuple[Height, Width] - - """ - - # Trick Generic __parameters__. - __class__ = typing.TypeVar - - def __iter__(self): - yield self.__unpacked__ - - def __init__(self, name, *, default=_marker): - self.__name__ = name - _DefaultMixin.__init__(self, default) - - # for pickling: - def_mod = _caller() - if def_mod != 'typing_extensions': - self.__module__ = def_mod - - self.__unpacked__ = Unpack[self] - - def __repr__(self): - return self.__name__ - - def __hash__(self): - return object.__hash__(self) - - def __eq__(self, other): - return self is other - - def __reduce__(self): - return self.__name__ - - def __init_subclass__(self, *args, **kwds): - if '_root' not in kwds: - raise TypeError("Cannot subclass special typing classes") - - -if hasattr(typing, "reveal_type"): - reveal_type = typing.reveal_type -else: - def reveal_type(__obj: T) -> T: - """Reveal the inferred type of a variable. - - When a static type checker encounters a call to ``reveal_type()``, - it will emit the inferred type of the argument:: - - x: int = 1 - reveal_type(x) - - Running a static type checker (e.g., ``mypy``) on this example - will produce output similar to 'Revealed type is "builtins.int"'. - - At runtime, the function prints the runtime type of the - argument and returns it unchanged. - - """ - print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr) - return __obj - - -if hasattr(typing, "assert_never"): - assert_never = typing.assert_never -else: - def assert_never(__arg: Never) -> Never: - """Assert to the type checker that a line of code is unreachable. - - Example:: - - def int_or_str(arg: int | str) -> None: - match arg: - case int(): - print("It's an int") - case str(): - print("It's a str") - case _: - assert_never(arg) - - If a type checker finds that a call to assert_never() is - reachable, it will emit an error. - - At runtime, this throws an exception when called. - - """ - raise AssertionError("Expected code to be unreachable") - - -if sys.version_info >= (3, 12): - # dataclass_transform exists in 3.11 but lacks the frozen_default parameter - dataclass_transform = typing.dataclass_transform -else: - def dataclass_transform( - *, - eq_default: bool = True, - order_default: bool = False, - kw_only_default: bool = False, - frozen_default: bool = False, - field_specifiers: typing.Tuple[ - typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], - ... - ] = (), - **kwargs: typing.Any, - ) -> typing.Callable[[T], T]: - """Decorator that marks a function, class, or metaclass as providing - dataclass-like behavior. - - Example: - - from pip._vendor.typing_extensions import dataclass_transform - - _T = TypeVar("_T") - - # Used on a decorator function - @dataclass_transform() - def create_model(cls: type[_T]) -> type[_T]: - ... - return cls - - @create_model - class CustomerModel: - id: int - name: str - - # Used on a base class - @dataclass_transform() - class ModelBase: ... - - class CustomerModel(ModelBase): - id: int - name: str - - # Used on a metaclass - @dataclass_transform() - class ModelMeta(type): ... - - class ModelBase(metaclass=ModelMeta): ... - - class CustomerModel(ModelBase): - id: int - name: str - - Each of the ``CustomerModel`` classes defined in this example will now - behave similarly to a dataclass created with the ``@dataclasses.dataclass`` - decorator. For example, the type checker will synthesize an ``__init__`` - method. - - The arguments to this decorator can be used to customize this behavior: - - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be - True or False if it is omitted by the caller. - - ``order_default`` indicates whether the ``order`` parameter is - assumed to be True or False if it is omitted by the caller. - - ``kw_only_default`` indicates whether the ``kw_only`` parameter is - assumed to be True or False if it is omitted by the caller. - - ``frozen_default`` indicates whether the ``frozen`` parameter is - assumed to be True or False if it is omitted by the caller. - - ``field_specifiers`` specifies a static list of supported classes - or functions that describe fields, similar to ``dataclasses.field()``. - - At runtime, this decorator records its arguments in the - ``__dataclass_transform__`` attribute on the decorated object. - - See PEP 681 for details. - - """ - def decorator(cls_or_fn): - cls_or_fn.__dataclass_transform__ = { - "eq_default": eq_default, - "order_default": order_default, - "kw_only_default": kw_only_default, - "frozen_default": frozen_default, - "field_specifiers": field_specifiers, - "kwargs": kwargs, - } - return cls_or_fn - return decorator - - -if hasattr(typing, "override"): - override = typing.override -else: - _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) - - def override(__arg: _F) -> _F: - """Indicate that a method is intended to override a method in a base class. - - Usage: - - class Base: - def method(self) -> None: ... - pass - - class Child(Base): - @override - def method(self) -> None: - super().method() - - When this decorator is applied to a method, the type checker will - validate that it overrides a method with the same name on a base class. - This helps prevent bugs that may occur when a base class is changed - without an equivalent change to a child class. - - There is no runtime checking of these properties. The decorator - sets the ``__override__`` attribute to ``True`` on the decorated object - to allow runtime introspection. - - See PEP 698 for details. - - """ - try: - __arg.__override__ = True - except (AttributeError, TypeError): - # Skip the attribute silently if it is not writable. - # AttributeError happens if the object has __slots__ or a - # read-only property, TypeError if it's a builtin class. - pass - return __arg - - -if hasattr(typing, "deprecated"): - deprecated = typing.deprecated -else: - _T = typing.TypeVar("_T") - - def deprecated( - __msg: str, - *, - category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, - stacklevel: int = 1, - ) -> typing.Callable[[_T], _T]: - """Indicate that a class, function or overload is deprecated. - - Usage: - - @deprecated("Use B instead") - class A: - pass - - @deprecated("Use g instead") - def f(): - pass - - @overload - @deprecated("int support is deprecated") - def g(x: int) -> int: ... - @overload - def g(x: str) -> int: ... - - When this decorator is applied to an object, the type checker - will generate a diagnostic on usage of the deprecated object. - - The warning specified by ``category`` will be emitted on use - of deprecated objects. For functions, that happens on calls; - for classes, on instantiation. If the ``category`` is ``None``, - no warning is emitted. The ``stacklevel`` determines where the - warning is emitted. If it is ``1`` (the default), the warning - is emitted at the direct caller of the deprecated object; if it - is higher, it is emitted further up the stack. - - The decorator sets the ``__deprecated__`` - attribute on the decorated object to the deprecation message - passed to the decorator. If applied to an overload, the decorator - must be after the ``@overload`` decorator for the attribute to - exist on the overload as returned by ``get_overloads()``. - - See PEP 702 for details. - - """ - def decorator(__arg: _T) -> _T: - if category is None: - __arg.__deprecated__ = __msg - return __arg - elif isinstance(__arg, type): - original_new = __arg.__new__ - has_init = __arg.__init__ is not object.__init__ - - @functools.wraps(original_new) - def __new__(cls, *args, **kwargs): - warnings.warn(__msg, category=category, stacklevel=stacklevel + 1) - if original_new is not object.__new__: - return original_new(cls, *args, **kwargs) - # Mirrors a similar check in object.__new__. - elif not has_init and (args or kwargs): - raise TypeError(f"{cls.__name__}() takes no arguments") - else: - return original_new(cls) - - __arg.__new__ = staticmethod(__new__) - __arg.__deprecated__ = __new__.__deprecated__ = __msg - return __arg - elif callable(__arg): - @functools.wraps(__arg) - def wrapper(*args, **kwargs): - warnings.warn(__msg, category=category, stacklevel=stacklevel + 1) - return __arg(*args, **kwargs) - - __arg.__deprecated__ = wrapper.__deprecated__ = __msg - return wrapper - else: - raise TypeError( - "@deprecated decorator with non-None category must be applied to " - f"a class or callable, not {__arg!r}" - ) - - return decorator - - -# We have to do some monkey patching to deal with the dual nature of -# Unpack/TypeVarTuple: -# - We want Unpack to be a kind of TypeVar so it gets accepted in -# Generic[Unpack[Ts]] -# - We want it to *not* be treated as a TypeVar for the purposes of -# counting generic parameters, so that when we subscript a generic, -# the runtime doesn't try to substitute the Unpack with the subscripted type. -if not hasattr(typing, "TypeVarTuple"): - typing._collect_type_vars = _collect_type_vars - typing._check_generic = _check_generic - - -# Backport typing.NamedTuple as it exists in Python 3.12. -# In 3.11, the ability to define generic `NamedTuple`s was supported. -# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. -# On 3.12, we added __orig_bases__ to call-based NamedTuples -# On 3.13, we deprecated kwargs-based NamedTuples -if sys.version_info >= (3, 13): - NamedTuple = typing.NamedTuple -else: - def _make_nmtuple(name, types, module, defaults=()): - fields = [n for n, t in types] - annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") - for n, t in types} - nm_tpl = collections.namedtuple(name, fields, - defaults=defaults, module=module) - nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations - # The `_field_types` attribute was removed in 3.9; - # in earlier versions, it is the same as the `__annotations__` attribute - if sys.version_info < (3, 9): - nm_tpl._field_types = annotations - return nm_tpl - - _prohibited_namedtuple_fields = typing._prohibited - _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) - - class _NamedTupleMeta(type): - def __new__(cls, typename, bases, ns): - assert _NamedTuple in bases - for base in bases: - if base is not _NamedTuple and base is not typing.Generic: - raise TypeError( - 'can only inherit from a NamedTuple type and Generic') - bases = tuple(tuple if base is _NamedTuple else base for base in bases) - types = ns.get('__annotations__', {}) - default_names = [] - for field_name in types: - if field_name in ns: - default_names.append(field_name) - elif default_names: - raise TypeError(f"Non-default namedtuple field {field_name} " - f"cannot follow default field" - f"{'s' if len(default_names) > 1 else ''} " - f"{', '.join(default_names)}") - nm_tpl = _make_nmtuple( - typename, types.items(), - defaults=[ns[n] for n in default_names], - module=ns['__module__'] - ) - nm_tpl.__bases__ = bases - if typing.Generic in bases: - if hasattr(typing, '_generic_class_getitem'): # 3.12+ - nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) - else: - class_getitem = typing.Generic.__class_getitem__.__func__ - nm_tpl.__class_getitem__ = classmethod(class_getitem) - # update from user namespace without overriding special namedtuple attributes - for key in ns: - if key in _prohibited_namedtuple_fields: - raise AttributeError("Cannot overwrite NamedTuple attribute " + key) - elif key not in _special_namedtuple_fields and key not in nm_tpl._fields: - setattr(nm_tpl, key, ns[key]) - if typing.Generic in bases: - nm_tpl.__init_subclass__() - return nm_tpl - - _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) - - def _namedtuple_mro_entries(bases): - assert NamedTuple in bases - return (_NamedTuple,) - - @_ensure_subclassable(_namedtuple_mro_entries) - def NamedTuple(__typename, __fields=_marker, **kwargs): - """Typed version of namedtuple. - - Usage:: - - class Employee(NamedTuple): - name: str - id: int - - This is equivalent to:: - - Employee = collections.namedtuple('Employee', ['name', 'id']) - - The resulting class has an extra __annotations__ attribute, giving a - dict that maps field names to types. (The field names are also in - the _fields attribute, which is part of the namedtuple API.) - An alternative equivalent functional syntax is also accepted:: - - Employee = NamedTuple('Employee', [('name', str), ('id', int)]) - """ - if __fields is _marker: - if kwargs: - deprecated_thing = "Creating NamedTuple classes using keyword arguments" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "Use the class-based or functional syntax instead." - ) - else: - deprecated_thing = "Failing to pass a value for the 'fields' parameter" - example = f"`{__typename} = NamedTuple({__typename!r}, [])`" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "To create a NamedTuple class with 0 fields " - "using the functional syntax, " - "pass an empty list, e.g. " - ) + example + "." - elif __fields is None: - if kwargs: - raise TypeError( - "Cannot pass `None` as the 'fields' parameter " - "and also specify fields using keyword arguments" - ) - else: - deprecated_thing = "Passing `None` as the 'fields' parameter" - example = f"`{__typename} = NamedTuple({__typename!r}, [])`" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "To create a NamedTuple class with 0 fields " - "using the functional syntax, " - "pass an empty list, e.g. " - ) + example + "." - elif kwargs: - raise TypeError("Either list of fields or keywords" - " can be provided to NamedTuple, not both") - if __fields is _marker or __fields is None: - warnings.warn( - deprecation_msg.format(name=deprecated_thing, remove="3.15"), - DeprecationWarning, - stacklevel=2, - ) - __fields = kwargs.items() - nt = _make_nmtuple(__typename, __fields, module=_caller()) - nt.__orig_bases__ = (NamedTuple,) - return nt - - # On 3.8+, alter the signature so that it matches typing.NamedTuple. - # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7, - # so just leave the signature as it is on 3.7. - if sys.version_info >= (3, 8): - _new_signature = '(typename, fields=None, /, **kwargs)' - if isinstance(NamedTuple, _types.FunctionType): - NamedTuple.__text_signature__ = _new_signature - else: - NamedTuple.__call__.__text_signature__ = _new_signature - - -if hasattr(collections.abc, "Buffer"): - Buffer = collections.abc.Buffer -else: - class Buffer(abc.ABC): - """Base class for classes that implement the buffer protocol. - - The buffer protocol allows Python objects to expose a low-level - memory buffer interface. Before Python 3.12, it is not possible - to implement the buffer protocol in pure Python code, or even - to check whether a class implements the buffer protocol. In - Python 3.12 and higher, the ``__buffer__`` method allows access - to the buffer protocol from Python code, and the - ``collections.abc.Buffer`` ABC allows checking whether a class - implements the buffer protocol. - - To indicate support for the buffer protocol in earlier versions, - inherit from this ABC, either in a stub file or at runtime, - or use ABC registration. This ABC provides no methods, because - there is no Python-accessible methods shared by pre-3.12 buffer - classes. It is useful primarily for static checks. - - """ - - # As a courtesy, register the most common stdlib buffer classes. - Buffer.register(memoryview) - Buffer.register(bytearray) - Buffer.register(bytes) - - -# Backport of types.get_original_bases, available on 3.12+ in CPython -if hasattr(_types, "get_original_bases"): - get_original_bases = _types.get_original_bases -else: - def get_original_bases(__cls): - """Return the class's "original" bases prior to modification by `__mro_entries__`. - - Examples:: - - from typing import TypeVar, Generic - from pip._vendor.typing_extensions import NamedTuple, TypedDict - - T = TypeVar("T") - class Foo(Generic[T]): ... - class Bar(Foo[int], float): ... - class Baz(list[str]): ... - Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) - Spam = TypedDict("Spam", {"a": int, "b": str}) - - assert get_original_bases(Bar) == (Foo[int], float) - assert get_original_bases(Baz) == (list[str],) - assert get_original_bases(Eggs) == (NamedTuple,) - assert get_original_bases(Spam) == (TypedDict,) - assert get_original_bases(int) == (object,) - """ - try: - return __cls.__orig_bases__ - except AttributeError: - try: - return __cls.__bases__ - except AttributeError: - raise TypeError( - f'Expected an instance of type, not {type(__cls).__name__!r}' - ) from None - - -# NewType is a class on Python 3.10+, making it pickleable -# The error message for subclassing instances of NewType was improved on 3.11+ -if sys.version_info >= (3, 11): - NewType = typing.NewType -else: - class NewType: - """NewType creates simple unique types with almost zero - runtime overhead. NewType(name, tp) is considered a subtype of tp - by static type checkers. At runtime, NewType(name, tp) returns - a dummy callable that simply returns its argument. Usage:: - UserId = NewType('UserId', int) - def name_by_id(user_id: UserId) -> str: - ... - UserId('user') # Fails type check - name_by_id(42) # Fails type check - name_by_id(UserId(42)) # OK - num = UserId(5) + 1 # type: int - """ - - def __call__(self, obj): - return obj - - def __init__(self, name, tp): - self.__qualname__ = name - if '.' in name: - name = name.rpartition('.')[-1] - self.__name__ = name - self.__supertype__ = tp - def_mod = _caller() - if def_mod != 'typing_extensions': - self.__module__ = def_mod - - def __mro_entries__(self, bases): - # We defined __mro_entries__ to get a better error message - # if a user attempts to subclass a NewType instance. bpo-46170 - supercls_name = self.__name__ - - class Dummy: - def __init_subclass__(cls): - subcls_name = cls.__name__ - raise TypeError( - f"Cannot subclass an instance of NewType. " - f"Perhaps you were looking for: " - f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" - ) - - return (Dummy,) - - def __repr__(self): - return f'{self.__module__}.{self.__qualname__}' - - def __reduce__(self): - return self.__qualname__ - - if sys.version_info >= (3, 10): - # PEP 604 methods - # It doesn't make sense to have these methods on Python <3.10 - - def __or__(self, other): - return typing.Union[self, other] - - def __ror__(self, other): - return typing.Union[other, self] - - -if hasattr(typing, "TypeAliasType"): - TypeAliasType = typing.TypeAliasType -else: - def _is_unionable(obj): - """Corresponds to is_unionable() in unionobject.c in CPython.""" - return obj is None or isinstance(obj, ( - type, - _types.GenericAlias, - _types.UnionType, - TypeAliasType, - )) - - class TypeAliasType: - """Create named, parameterized type aliases. - - This provides a backport of the new `type` statement in Python 3.12: - - type ListOrSet[T] = list[T] | set[T] - - is equivalent to: - - T = TypeVar("T") - ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) - - The name ListOrSet can then be used as an alias for the type it refers to. - - The type_params argument should contain all the type parameters used - in the value of the type alias. If the alias is not generic, this - argument is omitted. - - Static type checkers should only support type aliases declared using - TypeAliasType that follow these rules: - - - The first argument (the name) must be a string literal. - - The TypeAliasType instance must be immediately assigned to a variable - of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, - as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). - - """ - - def __init__(self, name: str, value, *, type_params=()): - if not isinstance(name, str): - raise TypeError("TypeAliasType name must be a string") - self.__value__ = value - self.__type_params__ = type_params - - parameters = [] - for type_param in type_params: - if isinstance(type_param, TypeVarTuple): - parameters.extend(type_param) - else: - parameters.append(type_param) - self.__parameters__ = tuple(parameters) - def_mod = _caller() - if def_mod != 'typing_extensions': - self.__module__ = def_mod - # Setting this attribute closes the TypeAliasType from further modification - self.__name__ = name - - def __setattr__(self, __name: str, __value: object) -> None: - if hasattr(self, "__name__"): - self._raise_attribute_error(__name) - super().__setattr__(__name, __value) - - def __delattr__(self, __name: str) -> Never: - self._raise_attribute_error(__name) - - def _raise_attribute_error(self, name: str) -> Never: - # Match the Python 3.12 error messages exactly - if name == "__name__": - raise AttributeError("readonly attribute") - elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}: - raise AttributeError( - f"attribute '{name}' of 'typing.TypeAliasType' objects " - "is not writable" - ) - else: - raise AttributeError( - f"'typing.TypeAliasType' object has no attribute '{name}'" - ) - - def __repr__(self) -> str: - return self.__name__ - - def __getitem__(self, parameters): - if not isinstance(parameters, tuple): - parameters = (parameters,) - parameters = [ - typing._type_check( - item, f'Subscripting {self.__name__} requires a type.' - ) - for item in parameters - ] - return typing._GenericAlias(self, tuple(parameters)) - - def __reduce__(self): - return self.__name__ - - def __init_subclass__(cls, *args, **kwargs): - raise TypeError( - "type 'typing_extensions.TypeAliasType' is not an acceptable base type" - ) - - # The presence of this method convinces typing._type_check - # that TypeAliasTypes are types. - def __call__(self): - raise TypeError("Type alias is not callable") - - if sys.version_info >= (3, 10): - def __or__(self, right): - # For forward compatibility with 3.12, reject Unions - # that are not accepted by the built-in Union. - if not _is_unionable(right): - return NotImplemented - return typing.Union[self, right] - - def __ror__(self, left): - if not _is_unionable(left): - return NotImplemented - return typing.Union[left, self] - - -if hasattr(typing, "is_protocol"): - is_protocol = typing.is_protocol - get_protocol_members = typing.get_protocol_members -else: - def is_protocol(__tp: type) -> bool: - """Return True if the given type is a Protocol. - - Example:: - - >>> from typing_extensions import Protocol, is_protocol - >>> class P(Protocol): - ... def a(self) -> str: ... - ... b: int - >>> is_protocol(P) - True - >>> is_protocol(int) - False - """ - return ( - isinstance(__tp, type) - and getattr(__tp, '_is_protocol', False) - and __tp is not Protocol - and __tp is not getattr(typing, "Protocol", object()) - ) - - def get_protocol_members(__tp: type) -> typing.FrozenSet[str]: - """Return the set of members defined in a Protocol. - - Example:: - - >>> from typing_extensions import Protocol, get_protocol_members - >>> class P(Protocol): - ... def a(self) -> str: ... - ... b: int - >>> get_protocol_members(P) - frozenset({'a', 'b'}) - - Raise a TypeError for arguments that are not Protocols. - """ - if not is_protocol(__tp): - raise TypeError(f'{__tp!r} is not a Protocol') - if hasattr(__tp, '__protocol_attrs__'): - return frozenset(__tp.__protocol_attrs__) - return frozenset(_get_protocol_attrs(__tp)) - - -# Aliases for items that have always been in typing. -# Explicitly assign these (rather than using `from typing import *` at the top), -# so that we get a CI error if one of these is deleted from typing.py -# in a future version of Python -AbstractSet = typing.AbstractSet -AnyStr = typing.AnyStr -BinaryIO = typing.BinaryIO -Callable = typing.Callable -Collection = typing.Collection -Container = typing.Container -Dict = typing.Dict -ForwardRef = typing.ForwardRef -FrozenSet = typing.FrozenSet -Generator = typing.Generator -Generic = typing.Generic -Hashable = typing.Hashable -IO = typing.IO -ItemsView = typing.ItemsView -Iterable = typing.Iterable -Iterator = typing.Iterator -KeysView = typing.KeysView -List = typing.List -Mapping = typing.Mapping -MappingView = typing.MappingView -Match = typing.Match -MutableMapping = typing.MutableMapping -MutableSequence = typing.MutableSequence -MutableSet = typing.MutableSet -Optional = typing.Optional -Pattern = typing.Pattern -Reversible = typing.Reversible -Sequence = typing.Sequence -Set = typing.Set -Sized = typing.Sized -TextIO = typing.TextIO -Tuple = typing.Tuple -Union = typing.Union -ValuesView = typing.ValuesView -cast = typing.cast -no_type_check = typing.no_type_check -no_type_check_decorator = typing.no_type_check_decorator diff --git a/spaces/plzdontcry/dakubettergpt/src/main.css b/spaces/plzdontcry/dakubettergpt/src/main.css deleted file mode 100644 index 2dd6b3c9928b9276a5ac634805274ee45140d556..0000000000000000000000000000000000000000 --- a/spaces/plzdontcry/dakubettergpt/src/main.css +++ /dev/null @@ -1,283 +0,0 @@ -@import url(Roboto.css); - -@tailwind base; -@tailwind components; -@tailwind utilities; - -@layer base { - * { - box-sizing: border-box; - } - - body, - html { - height: 100%; - } - - body { - line-height: inherit; - margin: 0; - } - - .dark body, - .dark html { - --tw-bg-opacity: 1; - background-color: rgba(52, 53, 65, var(--tw-bg-opacity)); - } - - #root { - height: 100%; - } - - .markdown table { - --tw-border-spacing-x: 0px; - --tw-border-spacing-y: 0px; - border-collapse: separate; - border-spacing: var(--tw-border-spacing-x) var(--tw-border-spacing-y); - width: 100%; - } - .markdown th { - background-color: rgba(236, 236, 241, 0.2); - border-bottom-width: 1px; - border-left-width: 1px; - border-top-width: 1px; - padding: 0.25rem 0.75rem; - } - .markdown th:first-child { - border-top-left-radius: 0.375rem; - } - .markdown th:last-child { - border-right-width: 1px; - border-top-right-radius: 0.375rem; - } - .markdown td { - border-bottom-width: 1px; - border-left-width: 1px; - padding: 0.25rem 0.75rem; - } - .markdown td:last-child { - border-right-width: 1px; - } - .markdown tbody tr:last-child td:first-child { - border-bottom-left-radius: 0.375rem; - } - .markdown tbody tr:last-child td:last-child { - border-bottom-right-radius: 0.375rem; - } - - img { - @apply inline-block; - } - - input[type='range']::-webkit-slider-thumb { - -webkit-appearance: none; - @apply w-4; - @apply h-4; - @apply rounded-full; - background: rgb(25, 111, 191); - } - - ::-webkit-scrollbar { - height: 1rem; - width: 0.5rem; - } - - @media screen and (max-width: 768px) { - ::-webkit-scrollbar { - display: none; - scrollbar-width: none; /* Firefox */ - } - } - - .hide-scroll-bar::-webkit-scrollbar { - display: none; - scrollbar-width: none; /* Firefox */ - } - - ::-webkit-scrollbar-thumb { - --tw-border-opacity: 1; - background-color: rgba(217, 217, 227, 0.8); - border-color: rgba(255, 255, 255, var(--tw-border-opacity)); - border-radius: 9999px; - border-width: 1px; - } - - ::-webkit-scrollbar-thumb:hover { - background-color: rgba(217, 217, 227, 0.6); - } - - .dark ::-webkit-scrollbar-thumb { - --tw-bg-opacity: 1; - background-color: rgba(86, 88, 105, var(--tw-bg-opacity)); - } - - .dark ::-webkit-scrollbar-thumb:hover { - background-color: rgba(217, 217, 227, 0.8); - } - - ::-webkit-scrollbar-track { - background-color: transparent; - border-radius: 9999px; - } - - pre ::-webkit-scrollbar-thumb { - display: none; - } - pre { - scrollbar-width: 0; - } - - textarea:focus { - outline: none; - } - - a.link { - @apply underline dark:hover:text-white hover:text-black; - } -} - -@layer components { - .btn { - align-items: center; - border-color: transparent; - border-radius: 0.25rem; - border-width: 1px; - display: inline-flex; - font-size: 0.875rem; - line-height: 1.25rem; - padding: 0.5rem 0.75rem; - pointer-events: auto; - } - - .btn-neutral { - --tw-bg-opacity: 1; - --tw-text-opacity: 1; - background-color: rgba(255, 255, 255, var(--tw-bg-opacity)); - border-color: rgba(0, 0, 0, 0.1); - border-width: 1px; - color: rgba(64, 65, 79, var(--tw-text-opacity)); - font-size: 0.875rem; - line-height: 1.25rem; - } - - .btn-neutral:hover { - --tw-bg-opacity: 1; - background-color: rgba(236, 236, 241, var(--tw-bg-opacity)); - } - - .dark .btn-neutral { - --tw-border-opacity: 1; - --tw-bg-opacity: 1; - --tw-text-opacity: 1; - background-color: rgba(52, 53, 65, var(--tw-bg-opacity)); - border-color: rgba(86, 88, 105, var(--tw-border-opacity)); - color: rgba(217, 217, 227, var(--tw-text-opacity)); - } - - .dark .btn-neutral:hover { - --tw-bg-opacity: 1; - background-color: rgba(64, 65, 79, var(--tw-bg-opacity)); - } - - .btn-dark { - --tw-border-opacity: 1; - --tw-bg-opacity: 1; - --tw-text-opacity: 1; - background-color: rgba(52, 53, 65, var(--tw-bg-opacity)); - border-color: rgba(86, 88, 105, var(--tw-border-opacity)); - border-width: 1px; - color: rgba(255, 255, 255, var(--tw-text-opacity)); - } - - .btn-primary { - --tw-bg-opacity: 1; - --tw-text-opacity: 1; - background-color: rgba(16, 163, 127, var(--tw-bg-opacity)); - color: rgba(255, 255, 255, var(--tw-text-opacity)); - } - - .btn-primary:hover { - --tw-bg-opacity: 1; - background-color: rgba(26, 127, 100, var(--tw-bg-opacity)); - } - - .btn-small { - padding: 0.25rem 0.5rem; - } - - button.scroll-convo { - display: none; - } - - .markdown ol, - .markdown ul { - display: flex; - flex-direction: column; - padding-left: 1rem; - } - - .markdown ol li, - .markdown ol li > p, - .markdown ol ol, - .markdown ol ul, - .markdown ul li, - .markdown ul li > p, - .markdown ul ol, - .markdown ul ul { - margin: 0; - } - - .markdown ul li:before { - content: '•'; - font-size: 0.875rem; - line-height: 1.25rem; - margin-left: -1rem; - position: absolute; - } -} - -:not(pre) > code.hljs, -:not(pre) > code[class*='language-'] { - border-radius: 0.3em; - white-space: normal; -} -.hljs-comment { - color: hsla(0, 0%, 100%, 0.5); -} -.hljs-meta { - color: hsla(0, 0%, 100%, 0.6); -} -.hljs-built_in, -.hljs-class .hljs-title { - color: #e9950c; -} -.hljs-doctag, -.hljs-formula, -.hljs-keyword, -.hljs-literal { - color: #2e95d3; -} -.hljs-addition, -.hljs-attribute, -.hljs-meta-string, -.hljs-regexp, -.hljs-string { - color: #00a67d; -} -.hljs-attr, -.hljs-number, -.hljs-selector-attr, -.hljs-selector-class, -.hljs-selector-pseudo, -.hljs-template-variable, -.hljs-type, -.hljs-variable { - color: #df3079; -} -.hljs-bullet, -.hljs-link, -.hljs-selector-id, -.hljs-symbol, -.hljs-title { - color: #f22c3d; -} diff --git a/spaces/power2/JoJoGan-powerhow2/e4e/utils/train_utils.py b/spaces/power2/JoJoGan-powerhow2/e4e/utils/train_utils.py deleted file mode 100644 index 0c55177f7442010bc1fcc64de3d142585c22adc0..0000000000000000000000000000000000000000 --- a/spaces/power2/JoJoGan-powerhow2/e4e/utils/train_utils.py +++ /dev/null @@ -1,13 +0,0 @@ - -def aggregate_loss_dict(agg_loss_dict): - mean_vals = {} - for output in agg_loss_dict: - for key in output: - mean_vals[key] = mean_vals.setdefault(key, []) + [output[key]] - for key in mean_vals: - if len(mean_vals[key]) > 0: - mean_vals[key] = sum(mean_vals[key]) / len(mean_vals[key]) - else: - print('{} has no value'.format(key)) - mean_vals[key] = 0 - return mean_vals diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/ttLib/tables/V_V_A_R_.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/ttLib/tables/V_V_A_R_.py deleted file mode 100644 index a3665fea5ecc6bd4bf50b447de551994330aaca4..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/ttLib/tables/V_V_A_R_.py +++ /dev/null @@ -1,5 +0,0 @@ -from .otBase import BaseTTXConverter - - -class table_V_V_A_R_(BaseTTXConverter): - pass diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/frontend/assets/Index-4007450e.js b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/frontend/assets/Index-4007450e.js deleted file mode 100644 index 183fc95d56dea5a90075e993e3776c79148de3fa..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/templates/frontend/assets/Index-4007450e.js +++ /dev/null @@ -1,2 +0,0 @@ -import{B as Me}from"./Button-8eeccca1.js";import{S as Ne}from"./Index-c74a8b7c.js";import{B as Oe}from"./BlockLabel-e3970ebb.js";import{I as Ue}from"./IconButton-0233c52d.js";import{E as Fe}from"./Empty-eeaba2d1.js";import{S as Pe}from"./ShareButton-8c2e0671.js";import{D as Xe}from"./Download-696bd40c.js";import{I as je}from"./Image-eaba773f.js";import{n as We}from"./index-50ad4c77.js";/* empty css */import{M as Je}from"./ModifyUpload-41fec6c8.js";import{u as Ke}from"./utils-c3e3db58.js";import"./svelte/svelte.js";import"./Clear-2c7bae91.js";var se=Object.prototype.hasOwnProperty;function ue(e,l,t){for(t of e.keys())if(X(t,l))return t}function X(e,l){var t,n,i;if(e===l)return!0;if(e&&l&&(t=e.constructor)===l.constructor){if(t===Date)return e.getTime()===l.getTime();if(t===RegExp)return e.toString()===l.toString();if(t===Array){if((n=e.length)===l.length)for(;n--&&X(e[n],l[n]););return n===-1}if(t===Set){if(e.size!==l.size)return!1;for(n of e)if(i=n,i&&typeof i=="object"&&(i=ue(l,i),!i)||!l.has(i))return!1;return!0}if(t===Map){if(e.size!==l.size)return!1;for(n of e)if(i=n[0],i&&typeof i=="object"&&(i=ue(l,i),!i)||!X(n[1],l.get(i)))return!1;return!0}if(t===ArrayBuffer)e=new Uint8Array(e),l=new Uint8Array(l);else if(t===DataView){if((n=e.byteLength)===l.byteLength)for(;n--&&e.getInt8(n)===l.getInt8(n););return n===-1}if(ArrayBuffer.isView(e)){if((n=e.byteLength)===l.byteLength)for(;n--&&e[n]===l[n];);return n===-1}if(!t||typeof e=="object"){n=0;for(t in e)if(se.call(e,t)&&++n&&!se.call(l,t)||!(t in l)||!X(e[t],l[t]))return!1;return Object.keys(l).length===n}}return e!==e&&l!==l}async function Qe(e){return e?`
    ${(await Promise.all(e.map(async([t,n])=>t===null||!t.url?"":await Ke(t.url,"url")))).map(t=>``).join("")}
    `:""}const{SvelteComponent:Ye,add_iframe_resize_listener:Ze,add_render_callback:ze,append:S,attr:d,binding_callbacks:_e,bubble:ce,check_outros:W,create_component:O,destroy_component:U,destroy_each:Be,detach:T,element:D,empty:xe,ensure_array_like:Q,globals:$e,group_outros:J,init:el,insert:L,listen:K,mount_component:F,run_all:ll,safe_not_equal:tl,set_data:Se,set_style:q,space:C,src_url_equal:N,text:Ae,toggle_class:E,transition_in:B,transition_out:A}=window.__gradio__svelte__internal,{window:De}=$e,{createEventDispatcher:nl}=window.__gradio__svelte__internal,{tick:il}=window.__gradio__svelte__internal;function he(e,l,t){const n=e.slice();return n[39]=l[t],n[41]=t,n}function me(e,l,t){const n=e.slice();return n[42]=l[t],n[43]=l,n[41]=t,n}function ge(e){let l,t;return l=new Oe({props:{show_label:e[1],Icon:je,label:e[2]||"Gallery"}}),{c(){O(l.$$.fragment)},m(n,i){F(l,n,i),t=!0},p(n,i){const r={};i[0]&2&&(r.show_label=n[1]),i[0]&4&&(r.label=n[2]||"Gallery"),l.$set(r)},i(n){t||(B(l.$$.fragment,n),t=!0)},o(n){A(l.$$.fragment,n),t=!1},d(n){U(l,n)}}}function ol(e){let l,t,n,i,r,m,u=e[0]!==null&&e[7]&&de(e),_=e[9]&&ve(e),w=Q(e[12]),o=[];for(let a=0;ae[34].call(t)),E(t,"fixed-height",!e[6]||e[6]=="auto")},m(a,c){u&&u.m(a,c),L(a,l,c),L(a,t,c),S(t,n),_&&_.m(n,null),S(n,i);for(let f=0;f{u=null}),W()),a[9]?_?(_.p(a,c),c[0]&512&&B(_,1)):(_=ve(a),_.c(),B(_,1),_.m(n,i)):_&&(J(),A(_,1,1,()=>{_=null}),W()),c[0]&4097){w=Q(a[12]);let f;for(f=0;f{v=null}),W());const I={};if(y[0]&2048&&(I.i18n=g[11]),i.$set(I),(!k||y[0]&4097&&!N(u.src,_=g[12][g[0]].image.path))&&d(u,"src",_),(!k||y[0]&4097&&w!==(w=g[12][g[0]].caption||""))&&d(u,"alt",w),(!k||y[0]&4097&&o!==(o=g[12][g[0]].caption||null))&&d(u,"title",o),(!k||y[0]&4097)&&E(u,"with-caption",!!g[12][g[0]].caption),(!k||y[0]&4097)&&q(m,"height","calc(100% - "+(g[12][g[0]].caption?"80px":"60px")+")"),g[12][g[0]]?.caption?z?z.p(g,y):(z=be(g),z.c(),z.m(l,c)):z&&(z.d(1),z=null),y[0]&12289){b=Q(g[12]);let j;for(j=0;je[28](l,u),a=()=>e[28](null,u);function c(){return e[29](e[41])}return{c(){l=D("button"),t=D("img"),r=C(),N(t.src,n=e[42].image.path)||d(t,"src",n),d(t,"title",i=e[42].caption||null),d(t,"alt",""),d(t,"loading","lazy"),d(t,"class","svelte-fiatpe"),d(l,"class","thumbnail-item thumbnail-small svelte-fiatpe"),d(l,"aria-label",m="Thumbnail "+(e[41]+1)+" of "+e[12].length),E(l,"selected",e[0]===e[41])},m(f,k){L(f,l,k),S(l,t),S(l,r),o(),_||(w=K(l,"click",c),_=!0)},p(f,k){e=f,k[0]&4096&&!N(t.src,n=e[42].image.path)&&d(t,"src",n),k[0]&4096&&i!==(i=e[42].caption||null)&&d(t,"title",i),k[0]&4096&&m!==(m="Thumbnail "+(e[41]+1)+" of "+e[12].length)&&d(l,"aria-label",m),u!==e[41]&&(a(),u=e[41],o()),k[0]&1&&E(l,"selected",e[0]===e[41])},d(f){f&&T(l),a(),_=!1,w()}}}function ve(e){let l,t,n;return t=new Pe({props:{i18n:e[11],value:e[12],formatter:Qe}}),t.$on("share",e[31]),t.$on("error",e[32]),{c(){l=D("div"),O(t.$$.fragment),d(l,"class","icon-button svelte-fiatpe")},m(i,r){L(i,l,r),F(t,l,null),n=!0},p(i,r){const m={};r[0]&2048&&(m.i18n=i[11]),r[0]&4096&&(m.value=i[12]),t.$set(m)},i(i){n||(B(t.$$.fragment,i),n=!0)},o(i){A(t.$$.fragment,i),n=!1},d(i){i&&T(l),U(t)}}}function pe(e){let l,t=e[39].caption+"",n;return{c(){l=D("div"),n=Ae(t),d(l,"class","caption-label svelte-fiatpe")},m(i,r){L(i,l,r),S(l,n)},p(i,r){r[0]&4096&&t!==(t=i[39].caption+"")&&Se(n,t)},d(i){i&&T(l)}}}function ye(e){let l,t,n,i,r,m,u,_,w,o=e[39].caption&&pe(e);function a(){return e[33](e[41])}return{c(){l=D("button"),t=D("img"),r=C(),o&&o.c(),m=C(),d(t,"alt",n=e[39].caption||""),N(t.src,i=typeof e[39].image=="string"?e[39].image:e[39].image.url)||d(t,"src",i),d(t,"loading","lazy"),d(t,"class","svelte-fiatpe"),d(l,"class","thumbnail-item thumbnail-lg svelte-fiatpe"),d(l,"aria-label",u="Thumbnail "+(e[41]+1)+" of "+e[12].length),E(l,"selected",e[0]===e[41])},m(c,f){L(c,l,f),S(l,t),S(l,r),o&&o.m(l,null),S(l,m),_||(w=K(l,"click",a),_=!0)},p(c,f){e=c,f[0]&4096&&n!==(n=e[39].caption||"")&&d(t,"alt",n),f[0]&4096&&!N(t.src,i=typeof e[39].image=="string"?e[39].image:e[39].image.url)&&d(t,"src",i),e[39].caption?o?o.p(e,f):(o=pe(e),o.c(),o.m(l,m)):o&&(o.d(1),o=null),f[0]&4096&&u!==(u="Thumbnail "+(e[41]+1)+" of "+e[12].length)&&d(l,"aria-label",u),f[0]&1&&E(l,"selected",e[0]===e[41])},d(c){c&&T(l),o&&o.d(),_=!1,w()}}}function fl(e){let l,t;return l=new je({}),{c(){O(l.$$.fragment)},m(n,i){F(l,n,i),t=!0},i(n){t||(B(l.$$.fragment,n),t=!0)},o(n){A(l.$$.fragment,n),t=!1},d(n){U(l,n)}}}function rl(e){let l,t,n,i,r,m,u;ze(e[25]);let _=e[1]&&ge(e);const w=[al,ol],o=[];function a(c,f){return c[3]===null||c[12]===null||c[12].length===0?0:1}return t=a(e),n=o[t]=w[t](e),{c(){_&&_.c(),l=C(),n.c(),i=xe()},m(c,f){_&&_.m(c,f),L(c,l,f),o[t].m(c,f),L(c,i,f),r=!0,m||(u=K(De,"resize",e[25]),m=!0)},p(c,f){c[1]?_?(_.p(c,f),f[0]&2&&B(_,1)):(_=ge(c),_.c(),B(_,1),_.m(l.parentNode,l)):_&&(J(),A(_,1,1,()=>{_=null}),W());let k=t;t=a(c),t===k?o[t].p(c,f):(J(),A(o[k],1,1,()=>{o[k]=null}),W(),n=o[t],n?n.p(c,f):(n=o[t]=w[t](c),n.c()),B(n,1),n.m(i.parentNode,i))},i(c){r||(B(_),B(n),r=!0)},o(c){A(_),A(n),r=!1},d(c){c&&(T(l),T(i)),_&&_.d(c),o[t].d(c),m=!1,u()}}}function sl(e){return typeof e=="object"&&e!==null&&"data"in e}function ee(e){return sl(e)?e.path:typeof e=="string"?e:Array.isArray(e)?ee(e[0]):""}function ul(e,l,t){let n,i,{show_label:r=!0}=l,{label:m}=l,{root:u=""}=l,{proxy_url:_=null}=l,{value:w=null}=l,{columns:o=[2]}=l,{rows:a=void 0}=l,{height:c="auto"}=l,{preview:f}=l,{allow_preview:k=!0}=l,{object_fit:H="cover"}=l,{show_share_button:R=!1}=l,{show_download_button:v=!1}=l,{i18n:z}=l,{selected_index:b=null}=l;const p=nl();let g=!0,y=null,I=w;b===null&&f&&w?.length&&(b=0);let j=b;function M(s){const P=s.target,x=s.clientX,$=P.offsetWidth/2;x<$?t(0,b=n):t(0,b=i)}function Y(s){switch(s.code){case"Escape":s.preventDefault(),t(0,b=null);break;case"ArrowLeft":s.preventDefault(),t(0,b=n);break;case"ArrowRight":s.preventDefault(),t(0,b=i);break}}let V=[],G;async function Z(s){if(typeof s!="number"||(await il(),V[s]===void 0))return;V[s]?.focus();const{left:P,width:x}=G.getBoundingClientRect(),{left:fe,width:$}=V[s].getBoundingClientRect(),re=fe-P+$/2-x/2+G.scrollLeft;G&&typeof G.scrollTo=="function"&&G.scrollTo({left:re<0?0:re,behavior:"smooth"})}let h=0,ae=0;function Ie(){t(16,ae=De.innerHeight)}const Te=()=>t(0,b=null),Le=s=>M(s);function Ge(s,P){_e[s?"unshift":"push"](()=>{V[P]=s,t(13,V)})}const qe=s=>t(0,b=s);function Ce(s){_e[s?"unshift":"push"](()=>{G=s,t(14,G)})}function Ee(s){ce.call(this,e,s)}function He(s){ce.call(this,e,s)}const Re=s=>t(0,b=s);function Ve(){h=this.clientHeight,t(15,h)}return e.$$set=s=>{"show_label"in s&&t(1,r=s.show_label),"label"in s&&t(2,m=s.label),"root"in s&&t(19,u=s.root),"proxy_url"in s&&t(20,_=s.proxy_url),"value"in s&&t(3,w=s.value),"columns"in s&&t(4,o=s.columns),"rows"in s&&t(5,a=s.rows),"height"in s&&t(6,c=s.height),"preview"in s&&t(21,f=s.preview),"allow_preview"in s&&t(7,k=s.allow_preview),"object_fit"in s&&t(8,H=s.object_fit),"show_share_button"in s&&t(9,R=s.show_share_button),"show_download_button"in s&&t(10,v=s.show_download_button),"i18n"in s&&t(11,z=s.i18n),"selected_index"in s&&t(0,b=s.selected_index)},e.$$.update=()=>{e.$$.dirty[0]&4194312&&t(22,g=w==null||w.length==0?!0:g),e.$$.dirty[0]&1572872&&t(12,y=w===null?null:w.map(s=>({image:We(s.image,u,_),caption:s.caption}))),e.$$.dirty[0]&14680073&&(X(I,w)||(g?(t(0,b=f&&w?.length?0:null),t(22,g=!1)):t(0,b=b!==null&&w!==null&&bdl(n,"selected_index",_)),n.$on("change",e[23]),n.$on("select",e[24]),n.$on("share",e[25]),n.$on("error",e[26]),{c(){le(l.$$.fragment),t=zl(),le(n.$$.fragment)},m(o,a){ne(l,o,a),yl(o,t,a),ne(n,o,a),r=!0},p(o,a){const c=a&2097154?vl(m,[a&2097152&&{autoscroll:o[21].autoscroll},a&2097152&&{i18n:o[21].i18n},a&2&&kl(o[1])]):{};l.$set(c);const f={};a&8&&(f.label=o[3]),a&512&&(f.value=o[9]),a&4&&(f.show_label=o[2]),a&16&&(f.root=o[4]),a&32&&(f.proxy_url=o[5]),a&8192&&(f.columns=o[13]),a&16384&&(f.rows=o[14]),a&32768&&(f.height=o[15]),a&65536&&(f.preview=o[16]),a&262144&&(f.object_fit=o[18]),a&131072&&(f.allow_preview=o[17]),a&524288&&(f.show_share_button=o[19]),a&1048576&&(f.show_download_button=o[20]),a&2097152&&(f.i18n=o[21].i18n),!i&&a&1&&(i=!0,f.selected_index=o[0],ml(()=>i=!1)),n.$set(f)},i(o){r||(ie(l.$$.fragment,o),ie(n.$$.fragment,o),r=!0)},o(o){oe(l.$$.fragment,o),oe(n.$$.fragment,o),r=!1},d(o){o&&bl(t),te(l,o),te(n,o)}}}function Sl(e){let l,t;return l=new Me({props:{visible:e[8],variant:"solid",padding:!1,elem_id:e[6],elem_classes:e[7],container:e[10],scale:e[11],min_width:e[12],allow_overflow:!1,height:typeof e[15]=="number"?e[15]:void 0,$$slots:{default:[Bl]},$$scope:{ctx:e}}}),{c(){le(l.$$.fragment)},m(n,i){ne(l,n,i),t=!0},p(n,[i]){const r={};i&256&&(r.visible=n[8]),i&64&&(r.elem_id=n[6]),i&128&&(r.elem_classes=n[7]),i&1024&&(r.container=n[10]),i&2048&&(r.scale=n[11]),i&4096&&(r.min_width=n[12]),i&32768&&(r.height=typeof n[15]=="number"?n[15]:void 0),i&138404415&&(r.$$scope={dirty:i,ctx:n}),l.$set(r)},i(n){t||(ie(l.$$.fragment,n),t=!0)},o(n){oe(l.$$.fragment,n),t=!1},d(n){te(l,n)}}}function Al(e,l,t){let{loading_status:n}=l,{show_label:i}=l,{label:r}=l,{root:m}=l,{proxy_url:u}=l,{elem_id:_=""}=l,{elem_classes:w=[]}=l,{visible:o=!0}=l,{value:a=null}=l,{container:c=!0}=l,{scale:f=null}=l,{min_width:k=void 0}=l,{columns:H=[2]}=l,{rows:R=void 0}=l,{height:v="auto"}=l,{preview:z}=l,{allow_preview:b=!0}=l,{selected_index:p=null}=l,{object_fit:g="cover"}=l,{show_share_button:y=!1}=l,{show_download_button:I=!1}=l,{gradio:j}=l;function M(h){p=h,t(0,p)}const Y=()=>j.dispatch("change",a),V=h=>j.dispatch("select",h.detail),G=h=>j.dispatch("share",h.detail),Z=h=>j.dispatch("error",h.detail);return e.$$set=h=>{"loading_status"in h&&t(1,n=h.loading_status),"show_label"in h&&t(2,i=h.show_label),"label"in h&&t(3,r=h.label),"root"in h&&t(4,m=h.root),"proxy_url"in h&&t(5,u=h.proxy_url),"elem_id"in h&&t(6,_=h.elem_id),"elem_classes"in h&&t(7,w=h.elem_classes),"visible"in h&&t(8,o=h.visible),"value"in h&&t(9,a=h.value),"container"in h&&t(10,c=h.container),"scale"in h&&t(11,f=h.scale),"min_width"in h&&t(12,k=h.min_width),"columns"in h&&t(13,H=h.columns),"rows"in h&&t(14,R=h.rows),"height"in h&&t(15,v=h.height),"preview"in h&&t(16,z=h.preview),"allow_preview"in h&&t(17,b=h.allow_preview),"selected_index"in h&&t(0,p=h.selected_index),"object_fit"in h&&t(18,g=h.object_fit),"show_share_button"in h&&t(19,y=h.show_share_button),"show_download_button"in h&&t(20,I=h.show_download_button),"gradio"in h&&t(21,j=h.gradio)},[p,n,i,r,m,u,_,w,o,a,c,f,k,H,R,v,z,b,g,y,I,j,M,Y,V,G,Z]}class Fl extends hl{constructor(l){super(),pl(this,l,Al,Sl,jl,{loading_status:1,show_label:2,label:3,root:4,proxy_url:5,elem_id:6,elem_classes:7,visible:8,value:9,container:10,scale:11,min_width:12,columns:13,rows:14,height:15,preview:16,allow_preview:17,selected_index:0,object_fit:18,show_share_button:19,show_download_button:20,gradio:21})}}export{cl as BaseGallery,Fl as default}; -//# sourceMappingURL=Index-4007450e.js.map diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/themes/utils/theme_dropdown.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/themes/utils/theme_dropdown.py deleted file mode 100644 index c3d21bba7784a0b8b4bfd989cd83ccda52c4fdbc..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/gradio/themes/utils/theme_dropdown.py +++ /dev/null @@ -1,57 +0,0 @@ -import os -import pathlib - -from gradio.themes.utils import ThemeAsset - - -def create_theme_dropdown(): - import gradio as gr - - asset_path = pathlib.Path() / "themes" - themes = [] - for theme_asset in os.listdir(str(asset_path)): - themes.append( - (ThemeAsset(theme_asset), gr.Theme.load(str(asset_path / theme_asset))) - ) - - def make_else_if(theme_asset): - return f""" - else if (theme == '{str(theme_asset[0].version)}') {{ - var theme_css = `{theme_asset[1]._get_theme_css()}` - }}""" - - head, tail = themes[0], themes[1:] - if_statement = f""" - if (theme == "{str(head[0].version)}") {{ - var theme_css = `{head[1]._get_theme_css()}` - }} {" ".join(make_else_if(t) for t in tail)} - """ - - latest_to_oldest = sorted([t[0] for t in themes], key=lambda asset: asset.version)[ - ::-1 - ] - latest_to_oldest = [str(t.version) for t in latest_to_oldest] - - component = gr.Dropdown( - choices=latest_to_oldest, - value=latest_to_oldest[0], - render=False, - label="Select Version", - ).style(container=False) - - return ( - component, - f""" - (theme) => {{ - if (!document.querySelector('.theme-css')) {{ - var theme_elem = document.createElement('style'); - theme_elem.classList.add('theme-css'); - document.head.appendChild(theme_elem); - }} else {{ - var theme_elem = document.querySelector('.theme-css'); - }} - {if_statement} - theme_elem.innerHTML = theme_css; - }} - """, - ) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jinja2/async_utils.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jinja2/async_utils.py deleted file mode 100644 index 1a4f3892cef1a53632476933f2ce2d86fc31b10a..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/jinja2/async_utils.py +++ /dev/null @@ -1,84 +0,0 @@ -import inspect -import typing as t -from functools import WRAPPER_ASSIGNMENTS -from functools import wraps - -from .utils import _PassArg -from .utils import pass_eval_context - -V = t.TypeVar("V") - - -def async_variant(normal_func): # type: ignore - def decorator(async_func): # type: ignore - pass_arg = _PassArg.from_obj(normal_func) - need_eval_context = pass_arg is None - - if pass_arg is _PassArg.environment: - - def is_async(args: t.Any) -> bool: - return t.cast(bool, args[0].is_async) - - else: - - def is_async(args: t.Any) -> bool: - return t.cast(bool, args[0].environment.is_async) - - # Take the doc and annotations from the sync function, but the - # name from the async function. Pallets-Sphinx-Themes - # build_function_directive expects __wrapped__ to point to the - # sync function. - async_func_attrs = ("__module__", "__name__", "__qualname__") - normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs)) - - @wraps(normal_func, assigned=normal_func_attrs) - @wraps(async_func, assigned=async_func_attrs, updated=()) - def wrapper(*args, **kwargs): # type: ignore - b = is_async(args) - - if need_eval_context: - args = args[1:] - - if b: - return async_func(*args, **kwargs) - - return normal_func(*args, **kwargs) - - if need_eval_context: - wrapper = pass_eval_context(wrapper) - - wrapper.jinja_async_variant = True - return wrapper - - return decorator - - -_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)} - - -async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V": - # Avoid a costly call to isawaitable - if type(value) in _common_primitives: - return t.cast("V", value) - - if inspect.isawaitable(value): - return await t.cast("t.Awaitable[V]", value) - - return t.cast("V", value) - - -async def auto_aiter( - iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", -) -> "t.AsyncIterator[V]": - if hasattr(iterable, "__aiter__"): - async for item in t.cast("t.AsyncIterable[V]", iterable): - yield item - else: - for item in t.cast("t.Iterable[V]", iterable): - yield item - - -async def auto_to_list( - value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", -) -> t.List["V"]: - return [x async for x in auto_aiter(value)] diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/mdurl/_format.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/mdurl/_format.py deleted file mode 100644 index 12524ca626065183ec9974f3d7d08dadd4a7d3e8..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/mdurl/_format.py +++ /dev/null @@ -1,27 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from mdurl._url import URL - - -def format(url: URL) -> str: # noqa: A001 - result = "" - - result += url.protocol or "" - result += "//" if url.slashes else "" - result += url.auth + "@" if url.auth else "" - - if url.hostname and ":" in url.hostname: - # ipv6 address - result += "[" + url.hostname + "]" - else: - result += url.hostname or "" - - result += ":" + url.port if url.port else "" - result += url.pathname or "" - result += url.search or "" - result += url.hash or "" - - return result diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/conftest.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/conftest.py deleted file mode 100644 index b1b35448af1340cc7902787c8b7d5d0eacd77505..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/conftest.py +++ /dev/null @@ -1,2011 +0,0 @@ -""" -This file is very long and growing, but it was decided to not split it yet, as -it's still manageable (2020-03-17, ~1.1k LoC). See gh-31989 - -Instead of splitting it was decided to define sections here: -- Configuration / Settings -- Autouse fixtures -- Common arguments -- Missing values & co. -- Classes -- Indices -- Series' -- DataFrames -- Operators & Operations -- Data sets/files -- Time zones -- Dtypes -- Misc -""" -from __future__ import annotations - -from collections import abc -from datetime import ( - date, - datetime, - time, - timedelta, - timezone, -) -from decimal import Decimal -import operator -import os -from pathlib import Path -from typing import ( - TYPE_CHECKING, - Callable, -) - -from dateutil.tz import ( - tzlocal, - tzutc, -) -import hypothesis -from hypothesis import strategies as st -import numpy as np -import pytest -from pytz import ( - FixedOffset, - utc, -) - -import pandas.util._test_decorators as td - -from pandas.core.dtypes.dtypes import ( - DatetimeTZDtype, - IntervalDtype, -) - -import pandas as pd -from pandas import ( - DataFrame, - Interval, - Period, - Series, - Timedelta, - Timestamp, -) -import pandas._testing as tm -from pandas.core import ops -from pandas.core.indexes.api import ( - Index, - MultiIndex, -) -from pandas.util.version import Version - -if TYPE_CHECKING: - from collections.abc import ( - Hashable, - Iterator, - ) - -try: - import pyarrow as pa -except ImportError: - has_pyarrow = False -else: - del pa - has_pyarrow = True - -import zoneinfo - -try: - zoneinfo.ZoneInfo("UTC") -except zoneinfo.ZoneInfoNotFoundError: - zoneinfo = None # type: ignore[assignment] - - -# ---------------------------------------------------------------- -# Configuration / Settings -# ---------------------------------------------------------------- -# pytest - - -def pytest_addoption(parser) -> None: - parser.addoption( - "--no-strict-data-files", - action="store_false", - help="Don't fail if a test is skipped for missing data file.", - ) - - -def ignore_doctest_warning(item: pytest.Item, path: str, message: str) -> None: - """Ignore doctest warning. - - Parameters - ---------- - item : pytest.Item - pytest test item. - path : str - Module path to Python object, e.g. "pandas.core.frame.DataFrame.append". A - warning will be filtered when item.name ends with in given path. So it is - sufficient to specify e.g. "DataFrame.append". - message : str - Message to be filtered. - """ - if item.name.endswith(path): - item.add_marker(pytest.mark.filterwarnings(f"ignore:{message}")) - - -def pytest_collection_modifyitems(items, config) -> None: - is_doctest = config.getoption("--doctest-modules") or config.getoption( - "--doctest-cython", default=False - ) - - # Warnings from doctests that can be ignored; place reason in comment above. - # Each entry specifies (path, message) - see the ignore_doctest_warning function - ignored_doctest_warnings = [ - ("is_int64_dtype", "is_int64_dtype is deprecated"), - ("is_interval_dtype", "is_interval_dtype is deprecated"), - ("is_period_dtype", "is_period_dtype is deprecated"), - ("is_datetime64tz_dtype", "is_datetime64tz_dtype is deprecated"), - ("is_categorical_dtype", "is_categorical_dtype is deprecated"), - ("is_sparse", "is_sparse is deprecated"), - ("NDFrame.replace", "The 'method' keyword"), - ("NDFrame.replace", "Series.replace without 'value'"), - ("Series.idxmin", "The behavior of Series.idxmin"), - ("Series.idxmax", "The behavior of Series.idxmax"), - ("SeriesGroupBy.idxmin", "The behavior of Series.idxmin"), - ("SeriesGroupBy.idxmax", "The behavior of Series.idxmax"), - # Docstring divides by zero to show behavior difference - ("missing.mask_zero_div_zero", "divide by zero encountered"), - ( - "to_pydatetime", - "The behavior of DatetimeProperties.to_pydatetime is deprecated", - ), - ( - "pandas.core.generic.NDFrame.bool", - "(Series|DataFrame).bool is now deprecated and will be removed " - "in future version of pandas", - ), - ( - "pandas.core.generic.NDFrame.first", - "first is deprecated and will be removed in a future version. " - "Please create a mask and filter using `.loc` instead", - ), - ( - "Resampler.fillna", - "DatetimeIndexResampler.fillna is deprecated", - ), - ( - "DataFrameGroupBy.fillna", - "DataFrameGroupBy.fillna with 'method' is deprecated", - ), - ( - "DataFrameGroupBy.fillna", - "DataFrame.fillna with 'method' is deprecated", - ), - ] - - for item in items: - if is_doctest: - # autouse=True for the add_doctest_imports can lead to expensive teardowns - # since doctest_namespace is a session fixture - item.add_marker(pytest.mark.usefixtures("add_doctest_imports")) - - for path, message in ignored_doctest_warnings: - ignore_doctest_warning(item, path, message) - - # mark all tests in the pandas/tests/frame directory with "arraymanager" - if "/frame/" in item.nodeid: - item.add_marker(pytest.mark.arraymanager) - - -hypothesis_health_checks = [hypothesis.HealthCheck.too_slow] -if Version(hypothesis.__version__) >= Version("6.83.2"): - hypothesis_health_checks.append(hypothesis.HealthCheck.differing_executors) - -# Hypothesis -hypothesis.settings.register_profile( - "ci", - # Hypothesis timing checks are tuned for scalars by default, so we bump - # them from 200ms to 500ms per test case as the global default. If this - # is too short for a specific test, (a) try to make it faster, and (b) - # if it really is slow add `@settings(deadline=...)` with a working value, - # or `deadline=None` to entirely disable timeouts for that test. - # 2022-02-09: Changed deadline from 500 -> None. Deadline leads to - # non-actionable, flaky CI failures (# GH 24641, 44969, 45118, 44969) - deadline=None, - suppress_health_check=tuple(hypothesis_health_checks), -) -hypothesis.settings.load_profile("ci") - -# Registering these strategies makes them globally available via st.from_type, -# which is use for offsets in tests/tseries/offsets/test_offsets_properties.py -for name in "MonthBegin MonthEnd BMonthBegin BMonthEnd".split(): - cls = getattr(pd.tseries.offsets, name) - st.register_type_strategy( - cls, st.builds(cls, n=st.integers(-99, 99), normalize=st.booleans()) - ) - -for name in "YearBegin YearEnd BYearBegin BYearEnd".split(): - cls = getattr(pd.tseries.offsets, name) - st.register_type_strategy( - cls, - st.builds( - cls, - n=st.integers(-5, 5), - normalize=st.booleans(), - month=st.integers(min_value=1, max_value=12), - ), - ) - -for name in "QuarterBegin QuarterEnd BQuarterBegin BQuarterEnd".split(): - cls = getattr(pd.tseries.offsets, name) - st.register_type_strategy( - cls, - st.builds( - cls, - n=st.integers(-24, 24), - normalize=st.booleans(), - startingMonth=st.integers(min_value=1, max_value=12), - ), - ) - - -@pytest.fixture -def add_doctest_imports(doctest_namespace) -> None: - """ - Make `np` and `pd` names available for doctests. - """ - doctest_namespace["np"] = np - doctest_namespace["pd"] = pd - - -# ---------------------------------------------------------------- -# Autouse fixtures -# ---------------------------------------------------------------- -@pytest.fixture(autouse=True) -def configure_tests() -> None: - """ - Configure settings for all tests and test modules. - """ - pd.set_option("chained_assignment", "raise") - - -# ---------------------------------------------------------------- -# Common arguments -# ---------------------------------------------------------------- -@pytest.fixture(params=[0, 1, "index", "columns"], ids=lambda x: f"axis={repr(x)}") -def axis(request): - """ - Fixture for returning the axis numbers of a DataFrame. - """ - return request.param - - -axis_frame = axis - - -@pytest.fixture(params=[1, "columns"], ids=lambda x: f"axis={repr(x)}") -def axis_1(request): - """ - Fixture for returning aliases of axis 1 of a DataFrame. - """ - return request.param - - -@pytest.fixture(params=[True, False, None]) -def observed(request): - """ - Pass in the observed keyword to groupby for [True, False] - This indicates whether categoricals should return values for - values which are not in the grouper [False / None], or only values which - appear in the grouper [True]. [None] is supported for future compatibility - if we decide to change the default (and would need to warn if this - parameter is not passed). - """ - return request.param - - -@pytest.fixture(params=[True, False, None]) -def ordered(request): - """ - Boolean 'ordered' parameter for Categorical. - """ - return request.param - - -@pytest.fixture(params=[True, False]) -def skipna(request): - """ - Boolean 'skipna' parameter. - """ - return request.param - - -@pytest.fixture(params=["first", "last", False]) -def keep(request): - """ - Valid values for the 'keep' parameter used in - .duplicated or .drop_duplicates - """ - return request.param - - -@pytest.fixture(params=["both", "neither", "left", "right"]) -def inclusive_endpoints_fixture(request): - """ - Fixture for trying all interval 'inclusive' parameters. - """ - return request.param - - -@pytest.fixture(params=["left", "right", "both", "neither"]) -def closed(request): - """ - Fixture for trying all interval closed parameters. - """ - return request.param - - -@pytest.fixture(params=["left", "right", "both", "neither"]) -def other_closed(request): - """ - Secondary closed fixture to allow parametrizing over all pairs of closed. - """ - return request.param - - -@pytest.fixture( - params=[ - None, - "gzip", - "bz2", - "zip", - "xz", - "tar", - pytest.param("zstd", marks=td.skip_if_no("zstandard")), - ] -) -def compression(request): - """ - Fixture for trying common compression types in compression tests. - """ - return request.param - - -@pytest.fixture( - params=[ - "gzip", - "bz2", - "zip", - "xz", - "tar", - pytest.param("zstd", marks=td.skip_if_no("zstandard")), - ] -) -def compression_only(request): - """ - Fixture for trying common compression types in compression tests excluding - uncompressed case. - """ - return request.param - - -@pytest.fixture(params=[True, False]) -def writable(request): - """ - Fixture that an array is writable. - """ - return request.param - - -@pytest.fixture(params=["inner", "outer", "left", "right"]) -def join_type(request): - """ - Fixture for trying all types of join operations. - """ - return request.param - - -@pytest.fixture(params=["nlargest", "nsmallest"]) -def nselect_method(request): - """ - Fixture for trying all nselect methods. - """ - return request.param - - -# ---------------------------------------------------------------- -# Missing values & co. -# ---------------------------------------------------------------- -@pytest.fixture(params=tm.NULL_OBJECTS, ids=lambda x: type(x).__name__) -def nulls_fixture(request): - """ - Fixture for each null type in pandas. - """ - return request.param - - -nulls_fixture2 = nulls_fixture # Generate cartesian product of nulls_fixture - - -@pytest.fixture(params=[None, np.nan, pd.NaT]) -def unique_nulls_fixture(request): - """ - Fixture for each null type in pandas, each null type exactly once. - """ - return request.param - - -# Generate cartesian product of unique_nulls_fixture: -unique_nulls_fixture2 = unique_nulls_fixture - - -@pytest.fixture(params=tm.NP_NAT_OBJECTS, ids=lambda x: type(x).__name__) -def np_nat_fixture(request): - """ - Fixture for each NaT type in numpy. - """ - return request.param - - -# Generate cartesian product of np_nat_fixture: -np_nat_fixture2 = np_nat_fixture - - -# ---------------------------------------------------------------- -# Classes -# ---------------------------------------------------------------- - - -@pytest.fixture(params=[DataFrame, Series]) -def frame_or_series(request): - """ - Fixture to parametrize over DataFrame and Series. - """ - return request.param - - -@pytest.fixture(params=[Index, Series], ids=["index", "series"]) -def index_or_series(request): - """ - Fixture to parametrize over Index and Series, made necessary by a mypy - bug, giving an error: - - List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]" - - See GH#29725 - """ - return request.param - - -# Generate cartesian product of index_or_series fixture: -index_or_series2 = index_or_series - - -@pytest.fixture(params=[Index, Series, pd.array], ids=["index", "series", "array"]) -def index_or_series_or_array(request): - """ - Fixture to parametrize over Index, Series, and ExtensionArray - """ - return request.param - - -@pytest.fixture(params=[Index, Series, DataFrame, pd.array], ids=lambda x: x.__name__) -def box_with_array(request): - """ - Fixture to test behavior for Index, Series, DataFrame, and pandas Array - classes - """ - return request.param - - -box_with_array2 = box_with_array - - -@pytest.fixture -def dict_subclass(): - """ - Fixture for a dictionary subclass. - """ - - class TestSubDict(dict): - def __init__(self, *args, **kwargs) -> None: - dict.__init__(self, *args, **kwargs) - - return TestSubDict - - -@pytest.fixture -def non_dict_mapping_subclass(): - """ - Fixture for a non-mapping dictionary subclass. - """ - - class TestNonDictMapping(abc.Mapping): - def __init__(self, underlying_dict) -> None: - self._data = underlying_dict - - def __getitem__(self, key): - return self._data.__getitem__(key) - - def __iter__(self) -> Iterator: - return self._data.__iter__() - - def __len__(self) -> int: - return self._data.__len__() - - return TestNonDictMapping - - -# ---------------------------------------------------------------- -# Indices -# ---------------------------------------------------------------- -@pytest.fixture -def multiindex_year_month_day_dataframe_random_data(): - """ - DataFrame with 3 level MultiIndex (year, month, day) covering - first 100 business days from 2000-01-01 with random data - """ - tdf = tm.makeTimeDataFrame(100) - ymd = tdf.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum() - # use int64 Index, to make sure things work - ymd.index = ymd.index.set_levels([lev.astype("i8") for lev in ymd.index.levels]) - ymd.index.set_names(["year", "month", "day"], inplace=True) - return ymd - - -@pytest.fixture -def lexsorted_two_level_string_multiindex() -> MultiIndex: - """ - 2-level MultiIndex, lexsorted, with string names. - """ - return MultiIndex( - levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], - codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], - names=["first", "second"], - ) - - -@pytest.fixture -def multiindex_dataframe_random_data( - lexsorted_two_level_string_multiindex, -) -> DataFrame: - """DataFrame with 2 level MultiIndex with random data""" - index = lexsorted_two_level_string_multiindex - return DataFrame( - np.random.default_rng(2).standard_normal((10, 3)), - index=index, - columns=Index(["A", "B", "C"], name="exp"), - ) - - -def _create_multiindex(): - """ - MultiIndex used to test the general functionality of this object - """ - - # See Also: tests.multi.conftest.idx - major_axis = Index(["foo", "bar", "baz", "qux"]) - minor_axis = Index(["one", "two"]) - - major_codes = np.array([0, 0, 1, 2, 3, 3]) - minor_codes = np.array([0, 1, 0, 1, 0, 1]) - index_names = ["first", "second"] - return MultiIndex( - levels=[major_axis, minor_axis], - codes=[major_codes, minor_codes], - names=index_names, - verify_integrity=False, - ) - - -def _create_mi_with_dt64tz_level(): - """ - MultiIndex with a level that is a tzaware DatetimeIndex. - """ - # GH#8367 round trip with pickle - return MultiIndex.from_product( - [[1, 2], ["a", "b"], pd.date_range("20130101", periods=3, tz="US/Eastern")], - names=["one", "two", "three"], - ) - - -indices_dict = { - "string": tm.makeStringIndex(100), - "datetime": tm.makeDateIndex(100), - "datetime-tz": tm.makeDateIndex(100, tz="US/Pacific"), - "period": tm.makePeriodIndex(100), - "timedelta": tm.makeTimedeltaIndex(100), - "range": tm.makeRangeIndex(100), - "int8": tm.makeIntIndex(100, dtype="int8"), - "int16": tm.makeIntIndex(100, dtype="int16"), - "int32": tm.makeIntIndex(100, dtype="int32"), - "int64": tm.makeIntIndex(100, dtype="int64"), - "uint8": tm.makeUIntIndex(100, dtype="uint8"), - "uint16": tm.makeUIntIndex(100, dtype="uint16"), - "uint32": tm.makeUIntIndex(100, dtype="uint32"), - "uint64": tm.makeUIntIndex(100, dtype="uint64"), - "float32": tm.makeFloatIndex(100, dtype="float32"), - "float64": tm.makeFloatIndex(100, dtype="float64"), - "bool-object": tm.makeBoolIndex(10).astype(object), - "bool-dtype": Index(np.random.default_rng(2).standard_normal(10) < 0), - "complex64": tm.makeNumericIndex(100, dtype="float64").astype("complex64"), - "complex128": tm.makeNumericIndex(100, dtype="float64").astype("complex128"), - "categorical": tm.makeCategoricalIndex(100), - "interval": tm.makeIntervalIndex(100), - "empty": Index([]), - "tuples": MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])), - "mi-with-dt64tz-level": _create_mi_with_dt64tz_level(), - "multi": _create_multiindex(), - "repeats": Index([0, 0, 1, 1, 2, 2]), - "nullable_int": Index(np.arange(100), dtype="Int64"), - "nullable_uint": Index(np.arange(100), dtype="UInt16"), - "nullable_float": Index(np.arange(100), dtype="Float32"), - "nullable_bool": Index(np.arange(100).astype(bool), dtype="boolean"), - "string-python": Index(pd.array(tm.makeStringIndex(100), dtype="string[python]")), -} -if has_pyarrow: - idx = Index(pd.array(tm.makeStringIndex(100), dtype="string[pyarrow]")) - indices_dict["string-pyarrow"] = idx - - -@pytest.fixture(params=indices_dict.keys()) -def index(request): - """ - Fixture for many "simple" kinds of indices. - - These indices are unlikely to cover corner cases, e.g. - - no names - - no NaTs/NaNs - - no values near implementation bounds - - ... - """ - # copy to avoid mutation, e.g. setting .name - return indices_dict[request.param].copy() - - -# Needed to generate cartesian product of indices -index_fixture2 = index - - -@pytest.fixture( - params=[ - key for key, value in indices_dict.items() if not isinstance(value, MultiIndex) - ] -) -def index_flat(request): - """ - index fixture, but excluding MultiIndex cases. - """ - key = request.param - return indices_dict[key].copy() - - -# Alias so we can test with cartesian product of index_flat -index_flat2 = index_flat - - -@pytest.fixture( - params=[ - key - for key, value in indices_dict.items() - if not ( - key.startswith(("int", "uint", "float")) - or key in ["range", "empty", "repeats", "bool-dtype"] - ) - and not isinstance(value, MultiIndex) - ] -) -def index_with_missing(request): - """ - Fixture for indices with missing values. - - Integer-dtype and empty cases are excluded because they cannot hold missing - values. - - MultiIndex is excluded because isna() is not defined for MultiIndex. - """ - - # GH 35538. Use deep copy to avoid illusive bug on np-dev - # GHA pipeline that writes into indices_dict despite copy - ind = indices_dict[request.param].copy(deep=True) - vals = ind.values.copy() - if request.param in ["tuples", "mi-with-dt64tz-level", "multi"]: - # For setting missing values in the top level of MultiIndex - vals = ind.tolist() - vals[0] = (None,) + vals[0][1:] - vals[-1] = (None,) + vals[-1][1:] - return MultiIndex.from_tuples(vals) - else: - vals[0] = None - vals[-1] = None - return type(ind)(vals) - - -# ---------------------------------------------------------------- -# Series' -# ---------------------------------------------------------------- -@pytest.fixture -def string_series() -> Series: - """ - Fixture for Series of floats with Index of unique strings - """ - s = tm.makeStringSeries() - s.name = "series" - return s - - -@pytest.fixture -def object_series() -> Series: - """ - Fixture for Series of dtype object with Index of unique strings - """ - s = tm.makeObjectSeries() - s.name = "objects" - return s - - -@pytest.fixture -def datetime_series() -> Series: - """ - Fixture for Series of floats with DatetimeIndex - """ - s = tm.makeTimeSeries() - s.name = "ts" - return s - - -def _create_series(index): - """Helper for the _series dict""" - size = len(index) - data = np.random.default_rng(2).standard_normal(size) - return Series(data, index=index, name="a", copy=False) - - -_series = { - f"series-with-{index_id}-index": _create_series(index) - for index_id, index in indices_dict.items() -} - - -@pytest.fixture -def series_with_simple_index(index) -> Series: - """ - Fixture for tests on series with changing types of indices. - """ - return _create_series(index) - - -@pytest.fixture -def series_with_multilevel_index() -> Series: - """ - Fixture with a Series with a 2-level MultiIndex. - """ - arrays = [ - ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], - ["one", "two", "one", "two", "one", "two", "one", "two"], - ] - tuples = zip(*arrays) - index = MultiIndex.from_tuples(tuples) - data = np.random.default_rng(2).standard_normal(8) - ser = Series(data, index=index) - ser.iloc[3] = np.nan - return ser - - -_narrow_series = { - f"{dtype.__name__}-series": tm.make_rand_series(name="a", dtype=dtype) - for dtype in tm.NARROW_NP_DTYPES -} - - -_index_or_series_objs = {**indices_dict, **_series, **_narrow_series} - - -@pytest.fixture(params=_index_or_series_objs.keys()) -def index_or_series_obj(request): - """ - Fixture for tests on indexes, series and series with a narrow dtype - copy to avoid mutation, e.g. setting .name - """ - return _index_or_series_objs[request.param].copy(deep=True) - - -_typ_objects_series = { - f"{dtype.__name__}-series": Series(dtype) for dtype in tm.PYTHON_DATA_TYPES -} - - -_index_or_series_memory_objs = { - **indices_dict, - **_series, - **_narrow_series, - **_typ_objects_series, -} - - -@pytest.fixture(params=_index_or_series_memory_objs.keys()) -def index_or_series_memory_obj(request): - """ - Fixture for tests on indexes, series, series with a narrow dtype and - series with empty objects type - copy to avoid mutation, e.g. setting .name - """ - return _index_or_series_memory_objs[request.param].copy(deep=True) - - -# ---------------------------------------------------------------- -# DataFrames -# ---------------------------------------------------------------- -@pytest.fixture -def int_frame() -> DataFrame: - """ - Fixture for DataFrame of ints with index of unique strings - - Columns are ['A', 'B', 'C', 'D'] - - A B C D - vpBeWjM651 1 0 1 0 - 5JyxmrP1En -1 0 0 0 - qEDaoD49U2 -1 1 0 0 - m66TkTfsFe 0 0 0 0 - EHPaNzEUFm -1 0 -1 0 - fpRJCevQhi 2 0 0 0 - OlQvnmfi3Q 0 0 -2 0 - ... .. .. .. .. - uB1FPlz4uP 0 0 0 1 - EcSe6yNzCU 0 0 -1 0 - L50VudaiI8 -1 1 -2 0 - y3bpw4nwIp 0 -1 0 0 - H0RdLLwrCT 1 1 0 0 - rY82K0vMwm 0 0 0 0 - 1OPIUjnkjk 2 0 0 0 - - [30 rows x 4 columns] - """ - return DataFrame(tm.getSeriesData()).astype("int64") - - -@pytest.fixture -def datetime_frame() -> DataFrame: - """ - Fixture for DataFrame of floats with DatetimeIndex - - Columns are ['A', 'B', 'C', 'D'] - - A B C D - 2000-01-03 -1.122153 0.468535 0.122226 1.693711 - 2000-01-04 0.189378 0.486100 0.007864 -1.216052 - 2000-01-05 0.041401 -0.835752 -0.035279 -0.414357 - 2000-01-06 0.430050 0.894352 0.090719 0.036939 - 2000-01-07 -0.620982 -0.668211 -0.706153 1.466335 - 2000-01-10 -0.752633 0.328434 -0.815325 0.699674 - 2000-01-11 -2.236969 0.615737 -0.829076 -1.196106 - ... ... ... ... ... - 2000-02-03 1.642618 -0.579288 0.046005 1.385249 - 2000-02-04 -0.544873 -1.160962 -0.284071 -1.418351 - 2000-02-07 -2.656149 -0.601387 1.410148 0.444150 - 2000-02-08 -1.201881 -1.289040 0.772992 -1.445300 - 2000-02-09 1.377373 0.398619 1.008453 -0.928207 - 2000-02-10 0.473194 -0.636677 0.984058 0.511519 - 2000-02-11 -0.965556 0.408313 -1.312844 -0.381948 - - [30 rows x 4 columns] - """ - return DataFrame(tm.getTimeSeriesData()) - - -@pytest.fixture -def float_frame() -> DataFrame: - """ - Fixture for DataFrame of floats with index of unique strings - - Columns are ['A', 'B', 'C', 'D']. - - A B C D - P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465 - qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901 - tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433 - wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651 - M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938 - QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053 - r78Jwns6dn -0.653707 0.883127 0.682199 0.206159 - ... ... ... ... ... - IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316 - lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999 - qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121 - yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962 - 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987 - eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871 - xSucinXxuV -1.263557 0.252799 -0.552247 0.400426 - - [30 rows x 4 columns] - """ - return DataFrame(tm.getSeriesData()) - - -@pytest.fixture -def mixed_type_frame() -> DataFrame: - """ - Fixture for DataFrame of float/int/string columns with RangeIndex - Columns are ['a', 'b', 'c', 'float32', 'int32']. - """ - return DataFrame( - { - "a": 1.0, - "b": 2, - "c": "foo", - "float32": np.array([1.0] * 10, dtype="float32"), - "int32": np.array([1] * 10, dtype="int32"), - }, - index=np.arange(10), - ) - - -@pytest.fixture -def rand_series_with_duplicate_datetimeindex() -> Series: - """ - Fixture for Series with a DatetimeIndex that has duplicates. - """ - dates = [ - datetime(2000, 1, 2), - datetime(2000, 1, 2), - datetime(2000, 1, 2), - datetime(2000, 1, 3), - datetime(2000, 1, 3), - datetime(2000, 1, 3), - datetime(2000, 1, 4), - datetime(2000, 1, 4), - datetime(2000, 1, 4), - datetime(2000, 1, 5), - ] - - return Series(np.random.default_rng(2).standard_normal(len(dates)), index=dates) - - -# ---------------------------------------------------------------- -# Scalars -# ---------------------------------------------------------------- -@pytest.fixture( - params=[ - (Interval(left=0, right=5), IntervalDtype("int64", "right")), - (Interval(left=0.1, right=0.5), IntervalDtype("float64", "right")), - (Period("2012-01", freq="M"), "period[M]"), - (Period("2012-02-01", freq="D"), "period[D]"), - ( - Timestamp("2011-01-01", tz="US/Eastern"), - DatetimeTZDtype(unit="s", tz="US/Eastern"), - ), - (Timedelta(seconds=500), "timedelta64[ns]"), - ] -) -def ea_scalar_and_dtype(request): - return request.param - - -# ---------------------------------------------------------------- -# Operators & Operations -# ---------------------------------------------------------------- - - -@pytest.fixture(params=tm.arithmetic_dunder_methods) -def all_arithmetic_operators(request): - """ - Fixture for dunder names for common arithmetic operations. - """ - return request.param - - -@pytest.fixture( - params=[ - operator.add, - ops.radd, - operator.sub, - ops.rsub, - operator.mul, - ops.rmul, - operator.truediv, - ops.rtruediv, - operator.floordiv, - ops.rfloordiv, - operator.mod, - ops.rmod, - operator.pow, - ops.rpow, - operator.eq, - operator.ne, - operator.lt, - operator.le, - operator.gt, - operator.ge, - operator.and_, - ops.rand_, - operator.xor, - ops.rxor, - operator.or_, - ops.ror_, - ] -) -def all_binary_operators(request): - """ - Fixture for operator and roperator arithmetic, comparison, and logical ops. - """ - return request.param - - -@pytest.fixture( - params=[ - operator.add, - ops.radd, - operator.sub, - ops.rsub, - operator.mul, - ops.rmul, - operator.truediv, - ops.rtruediv, - operator.floordiv, - ops.rfloordiv, - operator.mod, - ops.rmod, - operator.pow, - ops.rpow, - ] -) -def all_arithmetic_functions(request): - """ - Fixture for operator and roperator arithmetic functions. - - Notes - ----- - This includes divmod and rdivmod, whereas all_arithmetic_operators - does not. - """ - return request.param - - -_all_numeric_reductions = [ - "count", - "sum", - "max", - "min", - "mean", - "prod", - "std", - "var", - "median", - "kurt", - "skew", - "sem", -] - - -@pytest.fixture(params=_all_numeric_reductions) -def all_numeric_reductions(request): - """ - Fixture for numeric reduction names. - """ - return request.param - - -_all_boolean_reductions = ["all", "any"] - - -@pytest.fixture(params=_all_boolean_reductions) -def all_boolean_reductions(request): - """ - Fixture for boolean reduction names. - """ - return request.param - - -_all_reductions = _all_numeric_reductions + _all_boolean_reductions - - -@pytest.fixture(params=_all_reductions) -def all_reductions(request): - """ - Fixture for all (boolean + numeric) reduction names. - """ - return request.param - - -@pytest.fixture( - params=[ - operator.eq, - operator.ne, - operator.gt, - operator.ge, - operator.lt, - operator.le, - ] -) -def comparison_op(request): - """ - Fixture for operator module comparison functions. - """ - return request.param - - -@pytest.fixture(params=["__le__", "__lt__", "__ge__", "__gt__"]) -def compare_operators_no_eq_ne(request): - """ - Fixture for dunder names for compare operations except == and != - - * >= - * > - * < - * <= - """ - return request.param - - -@pytest.fixture( - params=["__and__", "__rand__", "__or__", "__ror__", "__xor__", "__rxor__"] -) -def all_logical_operators(request): - """ - Fixture for dunder names for common logical operations - - * | - * & - * ^ - """ - return request.param - - -_all_numeric_accumulations = ["cumsum", "cumprod", "cummin", "cummax"] - - -@pytest.fixture(params=_all_numeric_accumulations) -def all_numeric_accumulations(request): - """ - Fixture for numeric accumulation names - """ - return request.param - - -# ---------------------------------------------------------------- -# Data sets/files -# ---------------------------------------------------------------- -@pytest.fixture -def strict_data_files(pytestconfig): - """ - Returns the configuration for the test setting `--no-strict-data-files`. - """ - return pytestconfig.getoption("--no-strict-data-files") - - -@pytest.fixture -def tests_path() -> Path: - return Path(__file__).parent / "tests" - - -@pytest.fixture -def tests_io_data_path(tests_path) -> Path: - return tests_path / "io" / "data" - - -@pytest.fixture -def datapath(strict_data_files: str) -> Callable[..., str]: - """ - Get the path to a data file. - - Parameters - ---------- - path : str - Path to the file, relative to ``pandas/tests/`` - - Returns - ------- - path including ``pandas/tests``. - - Raises - ------ - ValueError - If the path doesn't exist and the --no-strict-data-files option is not set. - """ - BASE_PATH = os.path.join(os.path.dirname(__file__), "tests") - - def deco(*args): - path = os.path.join(BASE_PATH, *args) - if not os.path.exists(path): - if strict_data_files: - raise ValueError( - f"Could not find file {path} and --no-strict-data-files is not set." - ) - pytest.skip(f"Could not find {path}.") - return path - - return deco - - -@pytest.fixture -def iris(datapath) -> DataFrame: - """ - The iris dataset as a DataFrame. - """ - return pd.read_csv(datapath("io", "data", "csv", "iris.csv")) - - -# ---------------------------------------------------------------- -# Time zones -# ---------------------------------------------------------------- -TIMEZONES = [ - None, - "UTC", - "US/Eastern", - "Asia/Tokyo", - "dateutil/US/Pacific", - "dateutil/Asia/Singapore", - "+01:15", - "-02:15", - "UTC+01:15", - "UTC-02:15", - tzutc(), - tzlocal(), - FixedOffset(300), - FixedOffset(0), - FixedOffset(-300), - timezone.utc, - timezone(timedelta(hours=1)), - timezone(timedelta(hours=-1), name="foo"), -] -if zoneinfo is not None: - TIMEZONES.extend( - [ - zoneinfo.ZoneInfo("US/Pacific"), # type: ignore[list-item] - zoneinfo.ZoneInfo("UTC"), # type: ignore[list-item] - ] - ) -TIMEZONE_IDS = [repr(i) for i in TIMEZONES] - - -@td.parametrize_fixture_doc(str(TIMEZONE_IDS)) -@pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS) -def tz_naive_fixture(request): - """ - Fixture for trying timezones including default (None): {0} - """ - return request.param - - -@td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:])) -@pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:]) -def tz_aware_fixture(request): - """ - Fixture for trying explicit timezones: {0} - """ - return request.param - - -# Generate cartesian product of tz_aware_fixture: -tz_aware_fixture2 = tz_aware_fixture - - -_UTCS = ["utc", "dateutil/UTC", utc, tzutc(), timezone.utc] -if zoneinfo is not None: - _UTCS.append(zoneinfo.ZoneInfo("UTC")) - - -@pytest.fixture(params=_UTCS) -def utc_fixture(request): - """ - Fixture to provide variants of UTC timezone strings and tzinfo objects. - """ - return request.param - - -utc_fixture2 = utc_fixture - - -# ---------------------------------------------------------------- -# Dtypes -# ---------------------------------------------------------------- -@pytest.fixture(params=tm.STRING_DTYPES) -def string_dtype(request): - """ - Parametrized fixture for string dtypes. - - * str - * 'str' - * 'U' - """ - return request.param - - -@pytest.fixture( - params=[ - "string[python]", - pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")), - ] -) -def nullable_string_dtype(request): - """ - Parametrized fixture for string dtypes. - - * 'string[python]' - * 'string[pyarrow]' - """ - return request.param - - -@pytest.fixture( - params=[ - "python", - pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")), - pytest.param("pyarrow_numpy", marks=td.skip_if_no("pyarrow")), - ] -) -def string_storage(request): - """ - Parametrized fixture for pd.options.mode.string_storage. - - * 'python' - * 'pyarrow' - * 'pyarrow_numpy' - """ - return request.param - - -@pytest.fixture( - params=[ - "numpy_nullable", - pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")), - ] -) -def dtype_backend(request): - """ - Parametrized fixture for pd.options.mode.string_storage. - - * 'python' - * 'pyarrow' - """ - return request.param - - -# Alias so we can test with cartesian product of string_storage -string_storage2 = string_storage - - -@pytest.fixture(params=tm.BYTES_DTYPES) -def bytes_dtype(request): - """ - Parametrized fixture for bytes dtypes. - - * bytes - * 'bytes' - """ - return request.param - - -@pytest.fixture(params=tm.OBJECT_DTYPES) -def object_dtype(request): - """ - Parametrized fixture for object dtypes. - - * object - * 'object' - """ - return request.param - - -@pytest.fixture( - params=[ - "object", - "string[python]", - pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")), - pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")), - ] -) -def any_string_dtype(request): - """ - Parametrized fixture for string dtypes. - * 'object' - * 'string[python]' - * 'string[pyarrow]' - """ - return request.param - - -@pytest.fixture(params=tm.DATETIME64_DTYPES) -def datetime64_dtype(request): - """ - Parametrized fixture for datetime64 dtypes. - - * 'datetime64[ns]' - * 'M8[ns]' - """ - return request.param - - -@pytest.fixture(params=tm.TIMEDELTA64_DTYPES) -def timedelta64_dtype(request): - """ - Parametrized fixture for timedelta64 dtypes. - - * 'timedelta64[ns]' - * 'm8[ns]' - """ - return request.param - - -@pytest.fixture -def fixed_now_ts() -> Timestamp: - """ - Fixture emits fixed Timestamp.now() - """ - return Timestamp( - year=2021, month=1, day=1, hour=12, minute=4, second=13, microsecond=22 - ) - - -@pytest.fixture(params=tm.FLOAT_NUMPY_DTYPES) -def float_numpy_dtype(request): - """ - Parameterized fixture for float dtypes. - - * float - * 'float32' - * 'float64' - """ - return request.param - - -@pytest.fixture(params=tm.FLOAT_EA_DTYPES) -def float_ea_dtype(request): - """ - Parameterized fixture for float dtypes. - - * 'Float32' - * 'Float64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_FLOAT_DTYPES) -def any_float_dtype(request): - """ - Parameterized fixture for float dtypes. - - * float - * 'float32' - * 'float64' - * 'Float32' - * 'Float64' - """ - return request.param - - -@pytest.fixture(params=tm.COMPLEX_DTYPES) -def complex_dtype(request): - """ - Parameterized fixture for complex dtypes. - - * complex - * 'complex64' - * 'complex128' - """ - return request.param - - -@pytest.fixture(params=tm.SIGNED_INT_NUMPY_DTYPES) -def any_signed_int_numpy_dtype(request): - """ - Parameterized fixture for signed integer dtypes. - - * int - * 'int8' - * 'int16' - * 'int32' - * 'int64' - """ - return request.param - - -@pytest.fixture(params=tm.UNSIGNED_INT_NUMPY_DTYPES) -def any_unsigned_int_numpy_dtype(request): - """ - Parameterized fixture for unsigned integer dtypes. - - * 'uint8' - * 'uint16' - * 'uint32' - * 'uint64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_INT_NUMPY_DTYPES) -def any_int_numpy_dtype(request): - """ - Parameterized fixture for any integer dtype. - - * int - * 'int8' - * 'uint8' - * 'int16' - * 'uint16' - * 'int32' - * 'uint32' - * 'int64' - * 'uint64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_INT_EA_DTYPES) -def any_int_ea_dtype(request): - """ - Parameterized fixture for any nullable integer dtype. - - * 'UInt8' - * 'Int8' - * 'UInt16' - * 'Int16' - * 'UInt32' - * 'Int32' - * 'UInt64' - * 'Int64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_INT_DTYPES) -def any_int_dtype(request): - """ - Parameterized fixture for any nullable integer dtype. - - * int - * 'int8' - * 'uint8' - * 'int16' - * 'uint16' - * 'int32' - * 'uint32' - * 'int64' - * 'uint64' - * 'UInt8' - * 'Int8' - * 'UInt16' - * 'Int16' - * 'UInt32' - * 'Int32' - * 'UInt64' - * 'Int64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_INT_EA_DTYPES + tm.FLOAT_EA_DTYPES) -def any_numeric_ea_dtype(request): - """ - Parameterized fixture for any nullable integer dtype and - any float ea dtypes. - - * 'UInt8' - * 'Int8' - * 'UInt16' - * 'Int16' - * 'UInt32' - * 'Int32' - * 'UInt64' - * 'Int64' - * 'Float32' - * 'Float64' - """ - return request.param - - -# Unsupported operand types for + ("List[Union[str, ExtensionDtype, dtype[Any], -# Type[object]]]" and "List[str]") -@pytest.fixture( - params=tm.ALL_INT_EA_DTYPES - + tm.FLOAT_EA_DTYPES - + tm.ALL_INT_PYARROW_DTYPES_STR_REPR - + tm.FLOAT_PYARROW_DTYPES_STR_REPR # type: ignore[operator] -) -def any_numeric_ea_and_arrow_dtype(request): - """ - Parameterized fixture for any nullable integer dtype and - any float ea dtypes. - - * 'UInt8' - * 'Int8' - * 'UInt16' - * 'Int16' - * 'UInt32' - * 'Int32' - * 'UInt64' - * 'Int64' - * 'Float32' - * 'Float64' - * 'uint8[pyarrow]' - * 'int8[pyarrow]' - * 'uint16[pyarrow]' - * 'int16[pyarrow]' - * 'uint32[pyarrow]' - * 'int32[pyarrow]' - * 'uint64[pyarrow]' - * 'int64[pyarrow]' - * 'float32[pyarrow]' - * 'float64[pyarrow]' - """ - return request.param - - -@pytest.fixture(params=tm.SIGNED_INT_EA_DTYPES) -def any_signed_int_ea_dtype(request): - """ - Parameterized fixture for any signed nullable integer dtype. - - * 'Int8' - * 'Int16' - * 'Int32' - * 'Int64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_REAL_NUMPY_DTYPES) -def any_real_numpy_dtype(request): - """ - Parameterized fixture for any (purely) real numeric dtype. - - * int - * 'int8' - * 'uint8' - * 'int16' - * 'uint16' - * 'int32' - * 'uint32' - * 'int64' - * 'uint64' - * float - * 'float32' - * 'float64' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_REAL_DTYPES) -def any_real_numeric_dtype(request): - """ - Parameterized fixture for any (purely) real numeric dtype. - - * int - * 'int8' - * 'uint8' - * 'int16' - * 'uint16' - * 'int32' - * 'uint32' - * 'int64' - * 'uint64' - * float - * 'float32' - * 'float64' - - and associated ea dtypes. - """ - return request.param - - -@pytest.fixture(params=tm.ALL_NUMPY_DTYPES) -def any_numpy_dtype(request): - """ - Parameterized fixture for all numpy dtypes. - - * bool - * 'bool' - * int - * 'int8' - * 'uint8' - * 'int16' - * 'uint16' - * 'int32' - * 'uint32' - * 'int64' - * 'uint64' - * float - * 'float32' - * 'float64' - * complex - * 'complex64' - * 'complex128' - * str - * 'str' - * 'U' - * bytes - * 'bytes' - * 'datetime64[ns]' - * 'M8[ns]' - * 'timedelta64[ns]' - * 'm8[ns]' - * object - * 'object' - """ - return request.param - - -@pytest.fixture(params=tm.ALL_NUMERIC_DTYPES) -def any_numeric_dtype(request): - """ - Parameterized fixture for all numeric dtypes. - - * int - * 'int8' - * 'uint8' - * 'int16' - * 'uint16' - * 'int32' - * 'uint32' - * 'int64' - * 'uint64' - * float - * 'float32' - * 'float64' - * complex - * 'complex64' - * 'complex128' - * 'UInt8' - * 'Int8' - * 'UInt16' - * 'Int16' - * 'UInt32' - * 'Int32' - * 'UInt64' - * 'Int64' - * 'Float32' - * 'Float64' - """ - return request.param - - -# categoricals are handled separately -_any_skipna_inferred_dtype = [ - ("string", ["a", np.nan, "c"]), - ("string", ["a", pd.NA, "c"]), - ("mixed", ["a", pd.NaT, "c"]), # pd.NaT not considered valid by is_string_array - ("bytes", [b"a", np.nan, b"c"]), - ("empty", [np.nan, np.nan, np.nan]), - ("empty", []), - ("mixed-integer", ["a", np.nan, 2]), - ("mixed", ["a", np.nan, 2.0]), - ("floating", [1.0, np.nan, 2.0]), - ("integer", [1, np.nan, 2]), - ("mixed-integer-float", [1, np.nan, 2.0]), - ("decimal", [Decimal(1), np.nan, Decimal(2)]), - ("boolean", [True, np.nan, False]), - ("boolean", [True, pd.NA, False]), - ("datetime64", [np.datetime64("2013-01-01"), np.nan, np.datetime64("2018-01-01")]), - ("datetime", [Timestamp("20130101"), np.nan, Timestamp("20180101")]), - ("date", [date(2013, 1, 1), np.nan, date(2018, 1, 1)]), - ("complex", [1 + 1j, np.nan, 2 + 2j]), - # The following dtype is commented out due to GH 23554 - # ('timedelta64', [np.timedelta64(1, 'D'), - # np.nan, np.timedelta64(2, 'D')]), - ("timedelta", [timedelta(1), np.nan, timedelta(2)]), - ("time", [time(1), np.nan, time(2)]), - ("period", [Period(2013), pd.NaT, Period(2018)]), - ("interval", [Interval(0, 1), np.nan, Interval(0, 2)]), -] -ids, _ = zip(*_any_skipna_inferred_dtype) # use inferred type as fixture-id - - -@pytest.fixture(params=_any_skipna_inferred_dtype, ids=ids) -def any_skipna_inferred_dtype(request): - """ - Fixture for all inferred dtypes from _libs.lib.infer_dtype - - The covered (inferred) types are: - * 'string' - * 'empty' - * 'bytes' - * 'mixed' - * 'mixed-integer' - * 'mixed-integer-float' - * 'floating' - * 'integer' - * 'decimal' - * 'boolean' - * 'datetime64' - * 'datetime' - * 'date' - * 'timedelta' - * 'time' - * 'period' - * 'interval' - - Returns - ------- - inferred_dtype : str - The string for the inferred dtype from _libs.lib.infer_dtype - values : np.ndarray - An array of object dtype that will be inferred to have - `inferred_dtype` - - Examples - -------- - >>> from pandas._libs import lib - >>> - >>> def test_something(any_skipna_inferred_dtype): - ... inferred_dtype, values = any_skipna_inferred_dtype - ... # will pass - ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype - """ - inferred_dtype, values = request.param - values = np.array(values, dtype=object) # object dtype to avoid casting - - # correctness of inference tested in tests/dtypes/test_inference.py - return inferred_dtype, values - - -# ---------------------------------------------------------------- -# Misc -# ---------------------------------------------------------------- -@pytest.fixture -def ip(): - """ - Get an instance of IPython.InteractiveShell. - - Will raise a skip if IPython is not installed. - """ - pytest.importorskip("IPython", minversion="6.0.0") - from IPython.core.interactiveshell import InteractiveShell - - # GH#35711 make sure sqlite history file handle is not leaked - from traitlets.config import Config # isort:skip - - c = Config() - c.HistoryManager.hist_file = ":memory:" - - return InteractiveShell(config=c) - - -@pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"]) -def spmatrix(request): - """ - Yields scipy sparse matrix classes. - """ - sparse = pytest.importorskip("scipy.sparse") - - return getattr(sparse, request.param + "_matrix") - - -@pytest.fixture( - params=[ - getattr(pd.offsets, o) - for o in pd.offsets.__all__ - if issubclass(getattr(pd.offsets, o), pd.offsets.Tick) and o != "Tick" - ] -) -def tick_classes(request): - """ - Fixture for Tick based datetime offsets available for a time series. - """ - return request.param - - -@pytest.fixture(params=[None, lambda x: x]) -def sort_by_key(request): - """ - Simple fixture for testing keys in sorting methods. - Tests None (no key) and the identity key. - """ - return request.param - - -@pytest.fixture() -def fsspectest(): - pytest.importorskip("fsspec") - from fsspec import register_implementation - from fsspec.implementations.memory import MemoryFileSystem - from fsspec.registry import _registry as registry - - class TestMemoryFS(MemoryFileSystem): - protocol = "testmem" - test = [None] - - def __init__(self, **kwargs) -> None: - self.test[0] = kwargs.pop("test", None) - super().__init__(**kwargs) - - register_implementation("testmem", TestMemoryFS, clobber=True) - yield TestMemoryFS() - registry.pop("testmem", None) - TestMemoryFS.test[0] = None - TestMemoryFS.store.clear() - - -@pytest.fixture( - params=[ - ("foo", None, None), - ("Egon", "Venkman", None), - ("NCC1701D", "NCC1701D", "NCC1701D"), - # possibly-matching NAs - (np.nan, np.nan, np.nan), - (np.nan, pd.NaT, None), - (np.nan, pd.NA, None), - (pd.NA, pd.NA, pd.NA), - ] -) -def names(request) -> tuple[Hashable, Hashable, Hashable]: - """ - A 3-tuple of names, the first two for operands, the last for a result. - """ - return request.param - - -@pytest.fixture(params=[tm.setitem, tm.loc, tm.iloc]) -def indexer_sli(request): - """ - Parametrize over __setitem__, loc.__setitem__, iloc.__setitem__ - """ - return request.param - - -@pytest.fixture(params=[tm.loc, tm.iloc]) -def indexer_li(request): - """ - Parametrize over loc.__getitem__, iloc.__getitem__ - """ - return request.param - - -@pytest.fixture(params=[tm.setitem, tm.iloc]) -def indexer_si(request): - """ - Parametrize over __setitem__, iloc.__setitem__ - """ - return request.param - - -@pytest.fixture(params=[tm.setitem, tm.loc]) -def indexer_sl(request): - """ - Parametrize over __setitem__, loc.__setitem__ - """ - return request.param - - -@pytest.fixture(params=[tm.at, tm.loc]) -def indexer_al(request): - """ - Parametrize over at.__setitem__, loc.__setitem__ - """ - return request.param - - -@pytest.fixture(params=[tm.iat, tm.iloc]) -def indexer_ial(request): - """ - Parametrize over iat.__setitem__, iloc.__setitem__ - """ - return request.param - - -@pytest.fixture -def using_array_manager() -> bool: - """ - Fixture to check if the array manager is being used. - """ - return pd.options.mode.data_manager == "array" - - -@pytest.fixture -def using_copy_on_write() -> bool: - """ - Fixture to check if Copy-on-Write is enabled. - """ - return pd.options.mode.copy_on_write and pd.options.mode.data_manager == "block" - - -warsaws = ["Europe/Warsaw", "dateutil/Europe/Warsaw"] -if zoneinfo is not None: - warsaws.append(zoneinfo.ZoneInfo("Europe/Warsaw")) # type: ignore[arg-type] - - -@pytest.fixture(params=warsaws) -def warsaw(request) -> str: - """ - tzinfo for Europe/Warsaw using pytz, dateutil, or zoneinfo. - """ - return request.param - - -@pytest.fixture() -def arrow_string_storage(): - return ("pyarrow", "pyarrow_numpy") diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/datetimes/test_datetime.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/datetimes/test_datetime.py deleted file mode 100644 index e5e6d99c13e949a506f0d55f6fcc1f706a05a959..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/datetimes/test_datetime.py +++ /dev/null @@ -1,203 +0,0 @@ -from datetime import date - -import dateutil -import numpy as np -import pytest - -from pandas.compat.numpy import np_long - -import pandas as pd -from pandas import ( - DataFrame, - DatetimeIndex, - Index, - Timestamp, - date_range, - offsets, -) -import pandas._testing as tm - - -class TestDatetimeIndex: - def test_sub_datetime_preserves_freq(self, tz_naive_fixture): - # GH#48818 - dti = date_range("2016-01-01", periods=12, tz=tz_naive_fixture) - - res = dti - dti[0] - expected = pd.timedelta_range("0 Days", "11 Days") - tm.assert_index_equal(res, expected) - assert res.freq == expected.freq - - @pytest.mark.xfail( - reason="The inherited freq is incorrect bc dti.freq is incorrect " - "https://github.com/pandas-dev/pandas/pull/48818/files#r982793461" - ) - def test_sub_datetime_preserves_freq_across_dst(self): - # GH#48818 - ts = Timestamp("2016-03-11", tz="US/Pacific") - dti = date_range(ts, periods=4) - - res = dti - dti[0] - expected = pd.TimedeltaIndex( - [ - pd.Timedelta(days=0), - pd.Timedelta(days=1), - pd.Timedelta(days=2), - pd.Timedelta(days=2, hours=23), - ] - ) - tm.assert_index_equal(res, expected) - assert res.freq == expected.freq - - def test_time_overflow_for_32bit_machines(self): - # GH8943. On some machines NumPy defaults to np.int32 (for example, - # 32-bit Linux machines). In the function _generate_regular_range - # found in tseries/index.py, `periods` gets multiplied by `strides` - # (which has value 1e9) and since the max value for np.int32 is ~2e9, - # and since those machines won't promote np.int32 to np.int64, we get - # overflow. - periods = np_long(1000) - - idx1 = date_range(start="2000", periods=periods, freq="S") - assert len(idx1) == periods - - idx2 = date_range(end="2000", periods=periods, freq="S") - assert len(idx2) == periods - - def test_nat(self): - assert DatetimeIndex([np.nan])[0] is pd.NaT - - def test_week_of_month_frequency(self): - # GH 5348: "ValueError: Could not evaluate WOM-1SUN" shouldn't raise - d1 = date(2002, 9, 1) - d2 = date(2013, 10, 27) - d3 = date(2012, 9, 30) - idx1 = DatetimeIndex([d1, d2]) - idx2 = DatetimeIndex([d3]) - result_append = idx1.append(idx2) - expected = DatetimeIndex([d1, d2, d3]) - tm.assert_index_equal(result_append, expected) - result_union = idx1.union(idx2) - expected = DatetimeIndex([d1, d3, d2]) - tm.assert_index_equal(result_union, expected) - - # GH 5115 - result = date_range("2013-1-1", periods=4, freq="WOM-1SAT") - dates = ["2013-01-05", "2013-02-02", "2013-03-02", "2013-04-06"] - expected = DatetimeIndex(dates, freq="WOM-1SAT") - tm.assert_index_equal(result, expected) - - def test_append_nondatetimeindex(self): - rng = date_range("1/1/2000", periods=10) - idx = Index(["a", "b", "c", "d"]) - - result = rng.append(idx) - assert isinstance(result[0], Timestamp) - - def test_iteration_preserves_tz(self): - # see gh-8890 - index = date_range("2012-01-01", periods=3, freq="H", tz="US/Eastern") - - for i, ts in enumerate(index): - result = ts - expected = index[i] # pylint: disable=unnecessary-list-index-lookup - assert result == expected - - index = date_range( - "2012-01-01", periods=3, freq="H", tz=dateutil.tz.tzoffset(None, -28800) - ) - - for i, ts in enumerate(index): - result = ts - expected = index[i] # pylint: disable=unnecessary-list-index-lookup - assert result._repr_base == expected._repr_base - assert result == expected - - # 9100 - index = DatetimeIndex( - ["2014-12-01 03:32:39.987000-08:00", "2014-12-01 04:12:34.987000-08:00"] - ) - for i, ts in enumerate(index): - result = ts - expected = index[i] # pylint: disable=unnecessary-list-index-lookup - assert result._repr_base == expected._repr_base - assert result == expected - - @pytest.mark.parametrize("periods", [0, 9999, 10000, 10001]) - def test_iteration_over_chunksize(self, periods): - # GH21012 - - index = date_range("2000-01-01 00:00:00", periods=periods, freq="min") - num = 0 - for stamp in index: - assert index[num] == stamp - num += 1 - assert num == len(index) - - def test_misc_coverage(self): - rng = date_range("1/1/2000", periods=5) - result = rng.groupby(rng.day) - assert isinstance(next(iter(result.values()))[0], Timestamp) - - def test_groupby_function_tuple_1677(self): - df = DataFrame( - np.random.default_rng(2).random(100), - index=date_range("1/1/2000", periods=100), - ) - monthly_group = df.groupby(lambda x: (x.year, x.month)) - - result = monthly_group.mean() - assert isinstance(result.index[0], tuple) - - def assert_index_parameters(self, index): - assert index.freq == "40960N" - assert index.inferred_freq == "40960N" - - def test_ns_index(self): - nsamples = 400 - ns = int(1e9 / 24414) - dtstart = np.datetime64("2012-09-20T00:00:00") - - dt = dtstart + np.arange(nsamples) * np.timedelta64(ns, "ns") - freq = ns * offsets.Nano() - index = DatetimeIndex(dt, freq=freq, name="time") - self.assert_index_parameters(index) - - new_index = date_range(start=index[0], end=index[-1], freq=index.freq) - self.assert_index_parameters(new_index) - - def test_asarray_tz_naive(self): - # This shouldn't produce a warning. - idx = date_range("2000", periods=2) - # M8[ns] by default - result = np.asarray(idx) - - expected = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]") - tm.assert_numpy_array_equal(result, expected) - - # optionally, object - result = np.asarray(idx, dtype=object) - - expected = np.array([Timestamp("2000-01-01"), Timestamp("2000-01-02")]) - tm.assert_numpy_array_equal(result, expected) - - def test_asarray_tz_aware(self): - tz = "US/Central" - idx = date_range("2000", periods=2, tz=tz) - expected = np.array(["2000-01-01T06", "2000-01-02T06"], dtype="M8[ns]") - result = np.asarray(idx, dtype="datetime64[ns]") - - tm.assert_numpy_array_equal(result, expected) - - # Old behavior with no warning - result = np.asarray(idx, dtype="M8[ns]") - - tm.assert_numpy_array_equal(result, expected) - - # Future behavior with no warning - expected = np.array( - [Timestamp("2000-01-01", tz=tz), Timestamp("2000-01-02", tz=tz)] - ) - result = np.asarray(idx, dtype=object) - - tm.assert_numpy_array_equal(result, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/multi/test_copy.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/multi/test_copy.py deleted file mode 100644 index 2e09a580f9528bc8197d55c6a7533098e0129fa2..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/multi/test_copy.py +++ /dev/null @@ -1,96 +0,0 @@ -from copy import ( - copy, - deepcopy, -) - -import pytest - -from pandas import MultiIndex -import pandas._testing as tm - - -def assert_multiindex_copied(copy, original): - # Levels should be (at least, shallow copied) - tm.assert_copy(copy.levels, original.levels) - tm.assert_almost_equal(copy.codes, original.codes) - - # Labels doesn't matter which way copied - tm.assert_almost_equal(copy.codes, original.codes) - assert copy.codes is not original.codes - - # Names doesn't matter which way copied - assert copy.names == original.names - assert copy.names is not original.names - - # Sort order should be copied - assert copy.sortorder == original.sortorder - - -def test_copy(idx): - i_copy = idx.copy() - - assert_multiindex_copied(i_copy, idx) - - -def test_shallow_copy(idx): - i_copy = idx._view() - - assert_multiindex_copied(i_copy, idx) - - -def test_view(idx): - i_view = idx.view() - assert_multiindex_copied(i_view, idx) - - -@pytest.mark.parametrize("func", [copy, deepcopy]) -def test_copy_and_deepcopy(func): - idx = MultiIndex( - levels=[["foo", "bar"], ["fizz", "buzz"]], - codes=[[0, 0, 0, 1], [0, 0, 1, 1]], - names=["first", "second"], - ) - idx_copy = func(idx) - assert idx_copy is not idx - assert idx_copy.equals(idx) - - -@pytest.mark.parametrize("deep", [True, False]) -def test_copy_method(deep): - idx = MultiIndex( - levels=[["foo", "bar"], ["fizz", "buzz"]], - codes=[[0, 0, 0, 1], [0, 0, 1, 1]], - names=["first", "second"], - ) - idx_copy = idx.copy(deep=deep) - assert idx_copy.equals(idx) - - -@pytest.mark.parametrize("deep", [True, False]) -@pytest.mark.parametrize( - "kwarg, value", - [ - ("names", ["third", "fourth"]), - ], -) -def test_copy_method_kwargs(deep, kwarg, value): - # gh-12309: Check that the "name" argument as well other kwargs are honored - idx = MultiIndex( - levels=[["foo", "bar"], ["fizz", "buzz"]], - codes=[[0, 0, 0, 1], [0, 0, 1, 1]], - names=["first", "second"], - ) - idx_copy = idx.copy(**{kwarg: value, "deep": deep}) - assert getattr(idx_copy, kwarg) == value - - -def test_copy_deep_false_retains_id(): - # GH#47878 - idx = MultiIndex( - levels=[["foo", "bar"], ["fizz", "buzz"]], - codes=[[0, 0, 0, 1], [0, 0, 1, 1]], - names=["first", "second"], - ) - - res = idx.copy(deep=False) - assert res._id is idx._id diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/multi/test_duplicates.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/multi/test_duplicates.py deleted file mode 100644 index ee1edaa27f804ff18629b11ce54b597f833297fb..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/indexes/multi/test_duplicates.py +++ /dev/null @@ -1,344 +0,0 @@ -from itertools import product - -import numpy as np -import pytest - -from pandas._libs import ( - hashtable, - index as libindex, -) - -from pandas import ( - NA, - DatetimeIndex, - MultiIndex, - Series, -) -import pandas._testing as tm - - -@pytest.mark.parametrize("names", [None, ["first", "second"]]) -def test_unique(names): - mi = MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], names=names) - - res = mi.unique() - exp = MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names) - tm.assert_index_equal(res, exp) - - mi = MultiIndex.from_arrays([list("aaaa"), list("abab")], names=names) - res = mi.unique() - exp = MultiIndex.from_arrays([list("aa"), list("ab")], names=mi.names) - tm.assert_index_equal(res, exp) - - mi = MultiIndex.from_arrays([list("aaaa"), list("aaaa")], names=names) - res = mi.unique() - exp = MultiIndex.from_arrays([["a"], ["a"]], names=mi.names) - tm.assert_index_equal(res, exp) - - # GH #20568 - empty MI - mi = MultiIndex.from_arrays([[], []], names=names) - res = mi.unique() - tm.assert_index_equal(mi, res) - - -def test_unique_datetimelike(): - idx1 = DatetimeIndex( - ["2015-01-01", "2015-01-01", "2015-01-01", "2015-01-01", "NaT", "NaT"] - ) - idx2 = DatetimeIndex( - ["2015-01-01", "2015-01-01", "2015-01-02", "2015-01-02", "NaT", "2015-01-01"], - tz="Asia/Tokyo", - ) - result = MultiIndex.from_arrays([idx1, idx2]).unique() - - eidx1 = DatetimeIndex(["2015-01-01", "2015-01-01", "NaT", "NaT"]) - eidx2 = DatetimeIndex( - ["2015-01-01", "2015-01-02", "NaT", "2015-01-01"], tz="Asia/Tokyo" - ) - exp = MultiIndex.from_arrays([eidx1, eidx2]) - tm.assert_index_equal(result, exp) - - -@pytest.mark.parametrize("level", [0, "first", 1, "second"]) -def test_unique_level(idx, level): - # GH #17896 - with level= argument - result = idx.unique(level=level) - expected = idx.get_level_values(level).unique() - tm.assert_index_equal(result, expected) - - # With already unique level - mi = MultiIndex.from_arrays([[1, 3, 2, 4], [1, 3, 2, 5]], names=["first", "second"]) - result = mi.unique(level=level) - expected = mi.get_level_values(level) - tm.assert_index_equal(result, expected) - - # With empty MI - mi = MultiIndex.from_arrays([[], []], names=["first", "second"]) - result = mi.unique(level=level) - expected = mi.get_level_values(level) - tm.assert_index_equal(result, expected) - - -def test_duplicate_multiindex_codes(): - # GH 17464 - # Make sure that a MultiIndex with duplicate levels throws a ValueError - msg = r"Level values must be unique: \[[A', ]+\] on level 0" - with pytest.raises(ValueError, match=msg): - mi = MultiIndex([["A"] * 10, range(10)], [[0] * 10, range(10)]) - - # And that using set_levels with duplicate levels fails - mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) - msg = r"Level values must be unique: \[[AB', ]+\] on level 0" - with pytest.raises(ValueError, match=msg): - mi.set_levels([["A", "B", "A", "A", "B"], [2, 1, 3, -2, 5]]) - - -@pytest.mark.parametrize("names", [["a", "b", "a"], [1, 1, 2], [1, "a", 1]]) -def test_duplicate_level_names(names): - # GH18872, GH19029 - mi = MultiIndex.from_product([[0, 1]] * 3, names=names) - assert mi.names == names - - # With .rename() - mi = MultiIndex.from_product([[0, 1]] * 3) - mi = mi.rename(names) - assert mi.names == names - - # With .rename(., level=) - mi.rename(names[1], level=1, inplace=True) - mi = mi.rename([names[0], names[2]], level=[0, 2]) - assert mi.names == names - - -def test_duplicate_meta_data(): - # GH 10115 - mi = MultiIndex( - levels=[[0, 1], [0, 1, 2]], codes=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]] - ) - - for idx in [ - mi, - mi.set_names([None, None]), - mi.set_names([None, "Num"]), - mi.set_names(["Upper", "Num"]), - ]: - assert idx.has_duplicates - assert idx.drop_duplicates().names == idx.names - - -def test_has_duplicates(idx, idx_dup): - # see fixtures - assert idx.is_unique is True - assert idx.has_duplicates is False - assert idx_dup.is_unique is False - assert idx_dup.has_duplicates is True - - mi = MultiIndex( - levels=[[0, 1], [0, 1, 2]], codes=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]] - ) - assert mi.is_unique is False - assert mi.has_duplicates is True - - # single instance of NaN - mi_nan = MultiIndex( - levels=[["a", "b"], [0, 1]], codes=[[-1, 0, 0, 1, 1], [-1, 0, 1, 0, 1]] - ) - assert mi_nan.is_unique is True - assert mi_nan.has_duplicates is False - - # multiple instances of NaN - mi_nan_dup = MultiIndex( - levels=[["a", "b"], [0, 1]], codes=[[-1, -1, 0, 0, 1, 1], [-1, -1, 0, 1, 0, 1]] - ) - assert mi_nan_dup.is_unique is False - assert mi_nan_dup.has_duplicates is True - - -def test_has_duplicates_from_tuples(): - # GH 9075 - t = [ - ("x", "out", "z", 5, "y", "in", "z", 169), - ("x", "out", "z", 7, "y", "in", "z", 119), - ("x", "out", "z", 9, "y", "in", "z", 135), - ("x", "out", "z", 13, "y", "in", "z", 145), - ("x", "out", "z", 14, "y", "in", "z", 158), - ("x", "out", "z", 16, "y", "in", "z", 122), - ("x", "out", "z", 17, "y", "in", "z", 160), - ("x", "out", "z", 18, "y", "in", "z", 180), - ("x", "out", "z", 20, "y", "in", "z", 143), - ("x", "out", "z", 21, "y", "in", "z", 128), - ("x", "out", "z", 22, "y", "in", "z", 129), - ("x", "out", "z", 25, "y", "in", "z", 111), - ("x", "out", "z", 28, "y", "in", "z", 114), - ("x", "out", "z", 29, "y", "in", "z", 121), - ("x", "out", "z", 31, "y", "in", "z", 126), - ("x", "out", "z", 32, "y", "in", "z", 155), - ("x", "out", "z", 33, "y", "in", "z", 123), - ("x", "out", "z", 12, "y", "in", "z", 144), - ] - - mi = MultiIndex.from_tuples(t) - assert not mi.has_duplicates - - -@pytest.mark.parametrize("nlevels", [4, 8]) -@pytest.mark.parametrize("with_nulls", [True, False]) -def test_has_duplicates_overflow(nlevels, with_nulls): - # handle int64 overflow if possible - # no overflow with 4 - # overflow possible with 8 - codes = np.tile(np.arange(500), 2) - level = np.arange(500) - - if with_nulls: # inject some null values - codes[500] = -1 # common nan value - codes = [codes.copy() for i in range(nlevels)] - for i in range(nlevels): - codes[i][500 + i - nlevels // 2] = -1 - - codes += [np.array([-1, 1]).repeat(500)] - else: - codes = [codes] * nlevels + [np.arange(2).repeat(500)] - - levels = [level] * nlevels + [[0, 1]] - - # no dups - mi = MultiIndex(levels=levels, codes=codes) - assert not mi.has_duplicates - - # with a dup - if with_nulls: - - def f(a): - return np.insert(a, 1000, a[0]) - - codes = list(map(f, codes)) - mi = MultiIndex(levels=levels, codes=codes) - else: - values = mi.values.tolist() - mi = MultiIndex.from_tuples(values + [values[0]]) - - assert mi.has_duplicates - - -@pytest.mark.parametrize( - "keep, expected", - [ - ("first", np.array([False, False, False, True, True, False])), - ("last", np.array([False, True, True, False, False, False])), - (False, np.array([False, True, True, True, True, False])), - ], -) -def test_duplicated(idx_dup, keep, expected): - result = idx_dup.duplicated(keep=keep) - tm.assert_numpy_array_equal(result, expected) - - -@pytest.mark.arm_slow -def test_duplicated_hashtable_impl(keep, monkeypatch): - # GH 9125 - n, k = 6, 10 - levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)] - codes = [np.random.default_rng(2).choice(n, k * n) for _ in levels] - with monkeypatch.context() as m: - m.setattr(libindex, "_SIZE_CUTOFF", 50) - mi = MultiIndex(levels=levels, codes=codes) - - result = mi.duplicated(keep=keep) - expected = hashtable.duplicated(mi.values, keep=keep) - tm.assert_numpy_array_equal(result, expected) - - -@pytest.mark.parametrize("val", [101, 102]) -def test_duplicated_with_nan(val): - # GH5873 - mi = MultiIndex.from_arrays([[101, val], [3.5, np.nan]]) - assert not mi.has_duplicates - - tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(2, dtype="bool")) - - -@pytest.mark.parametrize("n", range(1, 6)) -@pytest.mark.parametrize("m", range(1, 5)) -def test_duplicated_with_nan_multi_shape(n, m): - # GH5873 - # all possible unique combinations, including nan - codes = product(range(-1, n), range(-1, m)) - mi = MultiIndex( - levels=[list("abcde")[:n], list("WXYZ")[:m]], - codes=np.random.default_rng(2).permutation(list(codes)).T, - ) - assert len(mi) == (n + 1) * (m + 1) - assert not mi.has_duplicates - - tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(len(mi), dtype="bool")) - - -def test_duplicated_drop_duplicates(): - # GH#4060 - idx = MultiIndex.from_arrays(([1, 2, 3, 1, 2, 3], [1, 1, 1, 1, 2, 2])) - - expected = np.array([False, False, False, True, False, False], dtype=bool) - duplicated = idx.duplicated() - tm.assert_numpy_array_equal(duplicated, expected) - assert duplicated.dtype == bool - expected = MultiIndex.from_arrays(([1, 2, 3, 2, 3], [1, 1, 1, 2, 2])) - tm.assert_index_equal(idx.drop_duplicates(), expected) - - expected = np.array([True, False, False, False, False, False]) - duplicated = idx.duplicated(keep="last") - tm.assert_numpy_array_equal(duplicated, expected) - assert duplicated.dtype == bool - expected = MultiIndex.from_arrays(([2, 3, 1, 2, 3], [1, 1, 1, 2, 2])) - tm.assert_index_equal(idx.drop_duplicates(keep="last"), expected) - - expected = np.array([True, False, False, True, False, False]) - duplicated = idx.duplicated(keep=False) - tm.assert_numpy_array_equal(duplicated, expected) - assert duplicated.dtype == bool - expected = MultiIndex.from_arrays(([2, 3, 2, 3], [1, 1, 2, 2])) - tm.assert_index_equal(idx.drop_duplicates(keep=False), expected) - - -@pytest.mark.parametrize( - "dtype", - [ - np.complex64, - np.complex128, - ], -) -def test_duplicated_series_complex_numbers(dtype): - # GH 17927 - expected = Series( - [False, False, False, True, False, False, False, True, False, True], - dtype=bool, - ) - result = Series( - [ - np.nan + np.nan * 1j, - 0, - 1j, - 1j, - 1, - 1 + 1j, - 1 + 2j, - 1 + 1j, - np.nan, - np.nan + np.nan * 1j, - ], - dtype=dtype, - ).duplicated() - tm.assert_series_equal(result, expected) - - -def test_midx_unique_ea_dtype(): - # GH#48335 - vals_a = Series([1, 2, NA, NA], dtype="Int64") - vals_b = np.array([1, 2, 3, 3]) - midx = MultiIndex.from_arrays([vals_a, vals_b], names=["a", "b"]) - result = midx.unique() - - exp_vals_a = Series([1, 2, NA], dtype="Int64") - exp_vals_b = np.array([1, 2, 3]) - expected = MultiIndex.from_arrays([exp_vals_a, exp_vals_b], names=["a", "b"]) - tm.assert_index_equal(result, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/reshape/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/reshape/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/resolution/base.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/resolution/base.py deleted file mode 100644 index 42dade18c1ec2b825f756dad4aaa89f2d9e6ce21..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/resolution/base.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Callable, List, Optional - -from pip._internal.req.req_install import InstallRequirement -from pip._internal.req.req_set import RequirementSet - -InstallRequirementProvider = Callable[ - [str, Optional[InstallRequirement]], InstallRequirement -] - - -class BaseResolver: - def resolve( - self, root_reqs: List[InstallRequirement], check_supported_wheels: bool - ) -> RequirementSet: - raise NotImplementedError() - - def get_installation_order( - self, req_set: RequirementSet - ) -> List[InstallRequirement]: - raise NotImplementedError() diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/utils/filetypes.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/utils/filetypes.py deleted file mode 100644 index 5948570178f3e6e79d1ff574241d09d4d8ed78de..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_internal/utils/filetypes.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Filetype information. -""" - -from typing import Tuple - -from pip._internal.utils.misc import splitext - -WHEEL_EXTENSION = ".whl" -BZ2_EXTENSIONS: Tuple[str, ...] = (".tar.bz2", ".tbz") -XZ_EXTENSIONS: Tuple[str, ...] = ( - ".tar.xz", - ".txz", - ".tlz", - ".tar.lz", - ".tar.lzma", -) -ZIP_EXTENSIONS: Tuple[str, ...] = (".zip", WHEEL_EXTENSION) -TAR_EXTENSIONS: Tuple[str, ...] = (".tar.gz", ".tgz", ".tar") -ARCHIVE_EXTENSIONS = ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS - - -def is_archive_file(name: str) -> bool: - """Return True if `name` is a considered as an archive file.""" - ext = splitext(name)[1].lower() - if ext in ARCHIVE_EXTENSIONS: - return True - return False diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/lexers/asn1.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/lexers/asn1.py deleted file mode 100644 index 30632cb4dfa12fa4423e6b57c1416fed7969f510..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/lexers/asn1.py +++ /dev/null @@ -1,179 +0,0 @@ -""" - pygments.lexers.asn1 - ~~~~~~~~~~~~~~~~~~~~ - - Pygments lexers for ASN.1. - - :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re - -from pygments.token import Comment, Operator, Keyword, Name, String, \ - Number, Punctuation, Whitespace -from pygments.lexer import RegexLexer, words, bygroups - -__all__ = ['Asn1Lexer'] - -SINGLE_WORD_KEYWORDS = [ - "ENCODED", - "ABSTRACT-SYNTAX", - "END", - "APPLICATION", - "EXPLICIT", - "IMPLICIT", - "AUTOMATIC", - "TAGS", - "BEGIN", - "EXTENSIBILITY", - "BY", - "FROM", - "COMPONENT", - "UNIVERSAL", - "COMPONENTS", - "CONSTRAINED", - "IMPLIED", - "DEFINITIONS", - "INCLUDES", - "PRIVATE", - "WITH", - "OF", -] - -OPERATOR_WORDS = [ - "EXCEPT", - "UNION", - "INTERSECTION", -] - -SINGLE_WORD_NAMESPACE_KEYWORDS = [ - "EXPORTS", - "IMPORTS", -] - -MULTI_WORDS_DECLARATIONS = [ - "SEQUENCE OF", - "SET OF", - "INSTANCE OF", - "WITH SYNTAX", -] - -SINGLE_WORDS_DECLARATIONS = [ - "SIZE", - "SEQUENCE", - "SET", - "CLASS", - "UNIQUE", - "DEFAULT", - "CHOICE", - "PATTERN", - "OPTIONAL", - "PRESENT", - "ABSENT", - "CONTAINING", - "ENUMERATED", - "ALL", -] - -TWO_WORDS_TYPES = [ - "OBJECT IDENTIFIER", - "BIT STRING", - "OCTET STRING", - "CHARACTER STRING", - "EMBEDDED PDV", -] - -SINGLE_WORD_TYPES = [ - "RELATIVE-OID", - "TYPE-IDENTIFIER", - "ObjectDescriptor", - "IA5String", - "INTEGER", - "ISO646String", - "T61String", - "BMPString", - "NumericString", - "TeletexString", - "GeneralizedTime", - "REAL", - "BOOLEAN", - "GeneralString", - "GraphicString", - "UniversalString", - "UTCTime", - "VisibleString", - "UTF8String", - "PrintableString", - "VideotexString", - "EXTERNAL", -] - - -def word_sequences(tokens): - return "(" + '|'.join(token.replace(' ', r'\s+') for token in tokens) + r')\b' - - -class Asn1Lexer(RegexLexer): - - """ - Lexer for ASN.1 module definition - - .. versionadded:: 2.16 - """ - - flags = re.MULTILINE - - name = 'ASN.1' - aliases = ['asn1'] - filenames = ["*.asn1"] - url = "https://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf" - - tokens = { - 'root': [ - # Whitespace: - (r'\s+', Whitespace), - # Comments: - (r'--.*$', Comment.Single), - (r'/\*', Comment.Multiline, 'comment'), - # Numbers: - (r'\d+\.\d*([eE][-+]?\d+)?', Number.Float), - (r'\d+', Number.Integer), - # Identifier: - (r"&?[a-z][-a-zA-Z0-9]*[a-zA-Z0-9]\b", Name.Variable), - # Constants: - (words(("TRUE", "FALSE", "NULL", "MINUS-INFINITY", "PLUS-INFINITY", "MIN", "MAX"), suffix=r'\b'), Keyword.Constant), - # Builtin types: - (word_sequences(TWO_WORDS_TYPES), Keyword.Type), - (words(SINGLE_WORD_TYPES, suffix=r'\b'), Keyword.Type), - # Other keywords: - (r"EXPORTS\s+ALL\b", Keyword.Namespace), - (words(SINGLE_WORD_NAMESPACE_KEYWORDS, suffix=r'\b'), Operator.Namespace), - (word_sequences(MULTI_WORDS_DECLARATIONS), Keyword.Declaration), - (words(SINGLE_WORDS_DECLARATIONS, suffix=r'\b'), Keyword.Declaration), - (words(OPERATOR_WORDS, suffix=r'\b'), Operator.Word), - (words(SINGLE_WORD_KEYWORDS), Keyword), - # Type identifier: - (r"&?[A-Z][-a-zA-Z0-9]*[a-zA-Z0-9]\b", Name.Type), - # Operators: - (r"(::=|\.\.\.|\.\.|\[\[|\]\]|\||\^)", Operator), - # Punctuation: - (r"(\.|,|\{|\}|\(|\)|\[|\])", Punctuation), - # String: - (r'"', String, 'string'), - # Binary string: - (r"('[01 ]*')(B)\b", bygroups(String, String.Affix)), - (r"('[0-9A-F ]*')(H)\b",bygroups(String, String.Affix)), - ], - 'comment': [ - (r'[^*/]+', Comment.Multiline), - (r'/\*', Comment.Multiline, '#push'), - (r'\*/', Comment.Multiline, '#pop'), - (r'[*/]', Comment.Multiline) - ], - 'string': [ - (r'""', String), - (r'"', String, "#pop"), - (r'[^"]', String), - ] - } diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/lexers/fantom.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/lexers/fantom.py deleted file mode 100644 index 7182d8184a99eb060cfc49b95243d48491af6380..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/lexers/fantom.py +++ /dev/null @@ -1,251 +0,0 @@ -""" - pygments.lexers.fantom - ~~~~~~~~~~~~~~~~~~~~~~ - - Lexer for the Fantom language. - - :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from string import Template - -from pygments.lexer import RegexLexer, include, bygroups, using, \ - this, default, words -from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ - Number, Punctuation, Literal, Whitespace - -__all__ = ['FantomLexer'] - - -class FantomLexer(RegexLexer): - """ - For Fantom source code. - - .. versionadded:: 1.5 - """ - name = 'Fantom' - aliases = ['fan'] - filenames = ['*.fan'] - mimetypes = ['application/x-fantom'] - - # often used regexes - def s(str): - return Template(str).substitute( - dict( - pod=r'[\"\w\.]+', - eos=r'\n|;', - id=r'[a-zA-Z_]\w*', - # all chars which can be part of type definition. Starts with - # either letter, or [ (maps), or | (funcs) - type=r'(?:\[|[a-zA-Z_]|\|)[:\w\[\]|\->?]*?', - ) - ) - - tokens = { - 'comments': [ - (r'(?s)/\*.*?\*/', Comment.Multiline), # Multiline - (r'//.*?$', Comment.Single), # Single line - # TODO: highlight references in fandocs - (r'\*\*.*?$', Comment.Special), # Fandoc - (r'#.*$', Comment.Single) # Shell-style - ], - 'literals': [ - (r'\b-?[\d_]+(ns|ms|sec|min|hr|day)', Number), # Duration - (r'\b-?[\d_]*\.[\d_]+(ns|ms|sec|min|hr|day)', Number), # Duration with dot - (r'\b-?(\d+)?\.\d+(f|F|d|D)?', Number.Float), # Float/Decimal - (r'\b-?0x[0-9a-fA-F_]+', Number.Hex), # Hex - (r'\b-?[\d_]+', Number.Integer), # Int - (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char), # Char - (r'"', Punctuation, 'insideStr'), # Opening quote - (r'`', Punctuation, 'insideUri'), # Opening accent - (r'\b(true|false|null)\b', Keyword.Constant), # Bool & null - (r'(?:(\w+)(::))?(\w+)(<\|)(.*?)(\|>)', # DSL - bygroups(Name.Namespace, Punctuation, Name.Class, - Punctuation, String, Punctuation)), - (r'(?:(\w+)(::))?(\w+)?(#)(\w+)?', # Type/slot literal - bygroups(Name.Namespace, Punctuation, Name.Class, - Punctuation, Name.Function)), - (r'\[,\]', Literal), # Empty list - (s(r'($type)(\[,\])'), # Typed empty list - bygroups(using(this, state='inType'), Literal)), - (r'\[:\]', Literal), # Empty Map - (s(r'($type)(\[:\])'), - bygroups(using(this, state='inType'), Literal)), - ], - 'insideStr': [ - (r'\\\\', String.Escape), # Escaped backslash - (r'\\"', String.Escape), # Escaped " - (r'\\`', String.Escape), # Escaped ` - (r'\$\w+', String.Interpol), # Subst var - (r'\$\{.*?\}', String.Interpol), # Subst expr - (r'"', Punctuation, '#pop'), # Closing quot - (r'.', String) # String content - ], - 'insideUri': [ # TODO: remove copy/paste str/uri - (r'\\\\', String.Escape), # Escaped backslash - (r'\\"', String.Escape), # Escaped " - (r'\\`', String.Escape), # Escaped ` - (r'\$\w+', String.Interpol), # Subst var - (r'\$\{.*?\}', String.Interpol), # Subst expr - (r'`', Punctuation, '#pop'), # Closing tick - (r'.', String.Backtick) # URI content - ], - 'protectionKeywords': [ - (r'\b(public|protected|private|internal)\b', Keyword), - ], - 'typeKeywords': [ - (r'\b(abstract|final|const|native|facet|enum)\b', Keyword), - ], - 'methodKeywords': [ - (r'\b(abstract|native|once|override|static|virtual|final)\b', - Keyword), - ], - 'fieldKeywords': [ - (r'\b(abstract|const|final|native|override|static|virtual|' - r'readonly)\b', Keyword) - ], - 'otherKeywords': [ - (words(( - 'try', 'catch', 'throw', 'finally', 'for', 'if', 'else', 'while', - 'as', 'is', 'isnot', 'switch', 'case', 'default', 'continue', - 'break', 'do', 'return', 'get', 'set'), prefix=r'\b', suffix=r'\b'), - Keyword), - (r'\b(it|this|super)\b', Name.Builtin.Pseudo), - ], - 'operators': [ - (r'\+\+|\-\-|\+|\-|\*|/|\|\||&&|<=>|<=|<|>=|>|=|!|\[|\]', Operator) - ], - 'inType': [ - (r'[\[\]|\->:?]', Punctuation), - (s(r'$id'), Name.Class), - default('#pop'), - - ], - 'root': [ - include('comments'), - include('protectionKeywords'), - include('typeKeywords'), - include('methodKeywords'), - include('fieldKeywords'), - include('literals'), - include('otherKeywords'), - include('operators'), - (r'using\b', Keyword.Namespace, 'using'), # Using stmt - (r'@\w+', Name.Decorator, 'facet'), # Symbol - (r'(class|mixin)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class), - 'inheritance'), # Inheritance list - - # Type var := val - (s(r'($type)([ \t]+)($id)(\s*)(:=)'), - bygroups(using(this, state='inType'), Whitespace, - Name.Variable, Whitespace, Operator)), - - # var := val - (s(r'($id)(\s*)(:=)'), - bygroups(Name.Variable, Whitespace, Operator)), - - # .someId( or ->someId( ### - (s(r'(\.|(?:\->))($id)(\s*)(\()'), - bygroups(Operator, Name.Function, Whitespace, Punctuation), - 'insideParen'), - - # .someId or ->someId - (s(r'(\.|(?:\->))($id)'), - bygroups(Operator, Name.Function)), - - # new makeXXX ( - (r'(new)(\s+)(make\w*)(\s*)(\()', - bygroups(Keyword, Whitespace, Name.Function, Whitespace, Punctuation), - 'insideMethodDeclArgs'), - - # Type name ( - (s(r'($type)([ \t]+)' # Return type and whitespace - r'($id)(\s*)(\()'), # method name + open brace - bygroups(using(this, state='inType'), Whitespace, - Name.Function, Whitespace, Punctuation), - 'insideMethodDeclArgs'), - - # ArgType argName, - (s(r'($type)(\s+)($id)(\s*)(,)'), - bygroups(using(this, state='inType'), Whitespace, Name.Variable, - Whitespace, Punctuation)), - - # ArgType argName) - # Covered in 'insideParen' state - - # ArgType argName -> ArgType| - (s(r'($type)(\s+)($id)(\s*)(\->)(\s*)($type)(\|)'), - bygroups(using(this, state='inType'), Whitespace, Name.Variable, - Whitespace, Punctuation, Whitespace, using(this, state='inType'), - Punctuation)), - - # ArgType argName| - (s(r'($type)(\s+)($id)(\s*)(\|)'), - bygroups(using(this, state='inType'), Whitespace, Name.Variable, - Whitespace, Punctuation)), - - # Type var - (s(r'($type)([ \t]+)($id)'), - bygroups(using(this, state='inType'), Whitespace, - Name.Variable)), - - (r'\(', Punctuation, 'insideParen'), - (r'\{', Punctuation, 'insideBrace'), - (r'\s+', Whitespace), - (r'.', Text) - ], - 'insideParen': [ - (r'\)', Punctuation, '#pop'), - include('root'), - ], - 'insideMethodDeclArgs': [ - (r'\)', Punctuation, '#pop'), - (s(r'($type)(\s+)($id)(\s*)(\))'), - bygroups(using(this, state='inType'), Whitespace, Name.Variable, - Whitespace, Punctuation), '#pop'), - include('root'), - ], - 'insideBrace': [ - (r'\}', Punctuation, '#pop'), - include('root'), - ], - 'inheritance': [ - (r'\s+', Whitespace), # Whitespace - (r':|,', Punctuation), - (r'(?:(\w+)(::))?(\w+)', - bygroups(Name.Namespace, Punctuation, Name.Class)), - (r'\{', Punctuation, '#pop') - ], - 'using': [ - (r'[ \t]+', Whitespace), # consume whitespaces - (r'(\[)(\w+)(\])', - bygroups(Punctuation, Comment.Special, Punctuation)), # ffi - (r'(\")?([\w.]+)(\")?', - bygroups(Punctuation, Name.Namespace, Punctuation)), # podname - (r'::', Punctuation, 'usingClass'), - default('#pop') - ], - 'usingClass': [ - (r'[ \t]+', Whitespace), # consume whitespaces - (r'(as)(\s+)(\w+)', - bygroups(Keyword.Declaration, Whitespace, Name.Class), '#pop:2'), - (r'[\w$]+', Name.Class), - default('#pop:2') # jump out to root state - ], - 'facet': [ - (r'\s+', Whitespace), - (r'\{', Punctuation, 'facetFields'), - default('#pop') - ], - 'facetFields': [ - include('comments'), - include('literals'), - include('operators'), - (r'\s+', Whitespace), - (r'(\s*)(\w+)(\s*)(=)', bygroups(Whitespace, Name, Whitespace, Operator)), - (r'\}', Punctuation, '#pop'), - (r'\s+', Whitespace), - (r'.', Text) - ], - } diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pyparsing/testing.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pyparsing/testing.py deleted file mode 100644 index 6a254c1c5e2584dae80f58d38e9a48aae7ec1237..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pyparsing/testing.py +++ /dev/null @@ -1,331 +0,0 @@ -# testing.py - -from contextlib import contextmanager -import typing - -from .core import ( - ParserElement, - ParseException, - Keyword, - __diag__, - __compat__, -) - - -class pyparsing_test: - """ - namespace class for classes useful in writing unit tests - """ - - class reset_pyparsing_context: - """ - Context manager to be used when writing unit tests that modify pyparsing config values: - - packrat parsing - - bounded recursion parsing - - default whitespace characters. - - default keyword characters - - literal string auto-conversion class - - __diag__ settings - - Example:: - - with reset_pyparsing_context(): - # test that literals used to construct a grammar are automatically suppressed - ParserElement.inlineLiteralsUsing(Suppress) - - term = Word(alphas) | Word(nums) - group = Group('(' + term[...] + ')') - - # assert that the '()' characters are not included in the parsed tokens - self.assertParseAndCheckList(group, "(abc 123 def)", ['abc', '123', 'def']) - - # after exiting context manager, literals are converted to Literal expressions again - """ - - def __init__(self): - self._save_context = {} - - def save(self): - self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS - self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS - - self._save_context[ - "literal_string_class" - ] = ParserElement._literalStringClass - - self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace - - self._save_context["packrat_enabled"] = ParserElement._packratEnabled - if ParserElement._packratEnabled: - self._save_context[ - "packrat_cache_size" - ] = ParserElement.packrat_cache.size - else: - self._save_context["packrat_cache_size"] = None - self._save_context["packrat_parse"] = ParserElement._parse - self._save_context[ - "recursion_enabled" - ] = ParserElement._left_recursion_enabled - - self._save_context["__diag__"] = { - name: getattr(__diag__, name) for name in __diag__._all_names - } - - self._save_context["__compat__"] = { - "collect_all_And_tokens": __compat__.collect_all_And_tokens - } - - return self - - def restore(self): - # reset pyparsing global state - if ( - ParserElement.DEFAULT_WHITE_CHARS - != self._save_context["default_whitespace"] - ): - ParserElement.set_default_whitespace_chars( - self._save_context["default_whitespace"] - ) - - ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"] - - Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"] - ParserElement.inlineLiteralsUsing( - self._save_context["literal_string_class"] - ) - - for name, value in self._save_context["__diag__"].items(): - (__diag__.enable if value else __diag__.disable)(name) - - ParserElement._packratEnabled = False - if self._save_context["packrat_enabled"]: - ParserElement.enable_packrat(self._save_context["packrat_cache_size"]) - else: - ParserElement._parse = self._save_context["packrat_parse"] - ParserElement._left_recursion_enabled = self._save_context[ - "recursion_enabled" - ] - - __compat__.collect_all_And_tokens = self._save_context["__compat__"] - - return self - - def copy(self): - ret = type(self)() - ret._save_context.update(self._save_context) - return ret - - def __enter__(self): - return self.save() - - def __exit__(self, *args): - self.restore() - - class TestParseResultsAsserts: - """ - A mixin class to add parse results assertion methods to normal unittest.TestCase classes. - """ - - def assertParseResultsEquals( - self, result, expected_list=None, expected_dict=None, msg=None - ): - """ - Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``, - and compare any defined results names with an optional ``expected_dict``. - """ - if expected_list is not None: - self.assertEqual(expected_list, result.as_list(), msg=msg) - if expected_dict is not None: - self.assertEqual(expected_dict, result.as_dict(), msg=msg) - - def assertParseAndCheckList( - self, expr, test_string, expected_list, msg=None, verbose=True - ): - """ - Convenience wrapper assert to test a parser element and input string, and assert that - the resulting ``ParseResults.asList()`` is equal to the ``expected_list``. - """ - result = expr.parse_string(test_string, parse_all=True) - if verbose: - print(result.dump()) - else: - print(result.as_list()) - self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg) - - def assertParseAndCheckDict( - self, expr, test_string, expected_dict, msg=None, verbose=True - ): - """ - Convenience wrapper assert to test a parser element and input string, and assert that - the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``. - """ - result = expr.parse_string(test_string, parseAll=True) - if verbose: - print(result.dump()) - else: - print(result.as_list()) - self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg) - - def assertRunTestResults( - self, run_tests_report, expected_parse_results=None, msg=None - ): - """ - Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of - list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped - with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``. - Finally, asserts that the overall ``runTests()`` success value is ``True``. - - :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests - :param expected_parse_results (optional): [tuple(str, list, dict, Exception)] - """ - run_test_success, run_test_results = run_tests_report - - if expected_parse_results is not None: - merged = [ - (*rpt, expected) - for rpt, expected in zip(run_test_results, expected_parse_results) - ] - for test_string, result, expected in merged: - # expected should be a tuple containing a list and/or a dict or an exception, - # and optional failure message string - # an empty tuple will skip any result validation - fail_msg = next( - (exp for exp in expected if isinstance(exp, str)), None - ) - expected_exception = next( - ( - exp - for exp in expected - if isinstance(exp, type) and issubclass(exp, Exception) - ), - None, - ) - if expected_exception is not None: - with self.assertRaises( - expected_exception=expected_exception, msg=fail_msg or msg - ): - if isinstance(result, Exception): - raise result - else: - expected_list = next( - (exp for exp in expected if isinstance(exp, list)), None - ) - expected_dict = next( - (exp for exp in expected if isinstance(exp, dict)), None - ) - if (expected_list, expected_dict) != (None, None): - self.assertParseResultsEquals( - result, - expected_list=expected_list, - expected_dict=expected_dict, - msg=fail_msg or msg, - ) - else: - # warning here maybe? - print(f"no validation for {test_string!r}") - - # do this last, in case some specific test results can be reported instead - self.assertTrue( - run_test_success, msg=msg if msg is not None else "failed runTests" - ) - - @contextmanager - def assertRaisesParseException(self, exc_type=ParseException, msg=None): - with self.assertRaises(exc_type, msg=msg): - yield - - @staticmethod - def with_line_numbers( - s: str, - start_line: typing.Optional[int] = None, - end_line: typing.Optional[int] = None, - expand_tabs: bool = True, - eol_mark: str = "|", - mark_spaces: typing.Optional[str] = None, - mark_control: typing.Optional[str] = None, - ) -> str: - """ - Helpful method for debugging a parser - prints a string with line and column numbers. - (Line and column numbers are 1-based.) - - :param s: tuple(bool, str - string to be printed with line and column numbers - :param start_line: int - (optional) starting line number in s to print (default=1) - :param end_line: int - (optional) ending line number in s to print (default=len(s)) - :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default - :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default="|") - :param mark_spaces: str - (optional) special character to display in place of spaces - :param mark_control: str - (optional) convert non-printing control characters to a placeholding - character; valid values: - - "unicode" - replaces control chars with Unicode symbols, such as "␍" and "␊" - - any single character string - replace control characters with given string - - None (default) - string is displayed as-is - - :return: str - input string with leading line numbers and column number headers - """ - if expand_tabs: - s = s.expandtabs() - if mark_control is not None: - mark_control = typing.cast(str, mark_control) - if mark_control == "unicode": - transtable_map = { - c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433)) - } - transtable_map[127] = 0x2421 - tbl = str.maketrans(transtable_map) - eol_mark = "" - else: - ord_mark_control = ord(mark_control) - tbl = str.maketrans( - {c: ord_mark_control for c in list(range(0, 32)) + [127]} - ) - s = s.translate(tbl) - if mark_spaces is not None and mark_spaces != " ": - if mark_spaces == "unicode": - tbl = str.maketrans({9: 0x2409, 32: 0x2423}) - s = s.translate(tbl) - else: - s = s.replace(" ", mark_spaces) - if start_line is None: - start_line = 1 - if end_line is None: - end_line = len(s) - end_line = min(end_line, len(s)) - start_line = min(max(1, start_line), end_line) - - if mark_control != "unicode": - s_lines = s.splitlines()[start_line - 1 : end_line] - else: - s_lines = [line + "␊" for line in s.split("␊")[start_line - 1 : end_line]] - if not s_lines: - return "" - - lineno_width = len(str(end_line)) - max_line_len = max(len(line) for line in s_lines) - lead = " " * (lineno_width + 1) - if max_line_len >= 99: - header0 = ( - lead - + "".join( - f"{' ' * 99}{(i + 1) % 100}" - for i in range(max(max_line_len // 100, 1)) - ) - + "\n" - ) - else: - header0 = "" - header1 = ( - header0 - + lead - + "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10))) - + "\n" - ) - header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n" - return ( - header1 - + header2 - + "\n".join( - f"{i:{lineno_width}d}:{line}{eol_mark}" - for i, line in enumerate(s_lines, start=start_line) - ) - + "\n" - ) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/tomlkit/_compat.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/tomlkit/_compat.py deleted file mode 100644 index 8e76b7fde372220eb512e58c25369d3f4bfc11a9..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/tomlkit/_compat.py +++ /dev/null @@ -1,22 +0,0 @@ -from __future__ import annotations - -import contextlib -import sys - -from typing import Any - - -PY38 = sys.version_info >= (3, 8) - - -def decode(string: Any, encodings: list[str] | None = None): - if not isinstance(string, bytes): - return string - - encodings = encodings or ["utf-8", "latin1", "ascii"] - - for encoding in encodings: - with contextlib.suppress(UnicodeEncodeError, UnicodeDecodeError): - return string.decode(encoding) - - return string.decode(encodings[0], errors="ignore") diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/typer/_completion_click8.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/typer/_completion_click8.py deleted file mode 100644 index 54e2b03d6f3390d8522c23592060e8383afb983b..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/typer/_completion_click8.py +++ /dev/null @@ -1,192 +0,0 @@ -import os -import re -import sys -from typing import Any, Dict, List, Tuple - -import click -import click.parser -import click.shell_completion - -from ._completion_shared import ( - COMPLETION_SCRIPT_BASH, - COMPLETION_SCRIPT_FISH, - COMPLETION_SCRIPT_POWER_SHELL, - COMPLETION_SCRIPT_ZSH, - Shells, -) - -try: - import shellingham -except ImportError: # pragma: nocover - shellingham = None - - -class BashComplete(click.shell_completion.BashComplete): - name = Shells.bash.value - source_template = COMPLETION_SCRIPT_BASH - - def source_vars(self) -> Dict[str, Any]: - return { - "complete_func": self.func_name, - "autocomplete_var": self.complete_var, - "prog_name": self.prog_name, - } - - def get_completion_args(self) -> Tuple[List[str], str]: - cwords = click.parser.split_arg_string(os.environ["COMP_WORDS"]) - cword = int(os.environ["COMP_CWORD"]) - args = cwords[1:cword] - - try: - incomplete = cwords[cword] - except IndexError: - incomplete = "" - - return args, incomplete - - def format_completion(self, item: click.shell_completion.CompletionItem) -> str: - # TODO: Explore replicating the new behavior from Click, with item types and - # triggering completion for files and directories - # return f"{item.type},{item.value}" - return f"{item.value}" - - def complete(self) -> str: - args, incomplete = self.get_completion_args() - completions = self.get_completions(args, incomplete) - out = [self.format_completion(item) for item in completions] - return "\n".join(out) - - -class ZshComplete(click.shell_completion.ZshComplete): - name = Shells.zsh.value - source_template = COMPLETION_SCRIPT_ZSH - - def source_vars(self) -> Dict[str, Any]: - return { - "complete_func": self.func_name, - "autocomplete_var": self.complete_var, - "prog_name": self.prog_name, - } - - def get_completion_args(self) -> Tuple[List[str], str]: - completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") - cwords = click.parser.split_arg_string(completion_args) - args = cwords[1:] - if args and not completion_args.endswith(" "): - incomplete = args[-1] - args = args[:-1] - else: - incomplete = "" - return args, incomplete - - def format_completion(self, item: click.shell_completion.CompletionItem) -> str: - def escape(s: str) -> str: - return ( - s.replace('"', '""') - .replace("'", "''") - .replace("$", "\\$") - .replace("`", "\\`") - ) - - # TODO: Explore replicating the new behavior from Click, pay attention to - # the difference with and without escape - # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}" - if item.help: - return f'"{escape(item.value)}":"{escape(item.help)}"' - else: - return f'"{escape(item.value)}"' - - def complete(self) -> str: - args, incomplete = self.get_completion_args() - completions = self.get_completions(args, incomplete) - res = [self.format_completion(item) for item in completions] - if res: - args_str = "\n".join(res) - return f"_arguments '*: :(({args_str}))'" - else: - return "_files" - - -class FishComplete(click.shell_completion.FishComplete): - name = Shells.fish.value - source_template = COMPLETION_SCRIPT_FISH - - def source_vars(self) -> Dict[str, Any]: - return { - "complete_func": self.func_name, - "autocomplete_var": self.complete_var, - "prog_name": self.prog_name, - } - - def get_completion_args(self) -> Tuple[List[str], str]: - completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") - cwords = click.parser.split_arg_string(completion_args) - args = cwords[1:] - if args and not completion_args.endswith(" "): - incomplete = args[-1] - args = args[:-1] - else: - incomplete = "" - return args, incomplete - - def format_completion(self, item: click.shell_completion.CompletionItem) -> str: - # TODO: Explore replicating the new behavior from Click, pay attention to - # the difference with and without formatted help - # if item.help: - # return f"{item.type},{item.value}\t{item.help}" - - # return f"{item.type},{item.value} - if item.help: - formatted_help = re.sub(r"\s", " ", item.help) - return f"{item.value}\t{formatted_help}" - else: - return f"{item.value}" - - def complete(self) -> str: - complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "") - args, incomplete = self.get_completion_args() - completions = self.get_completions(args, incomplete) - show_args = [self.format_completion(item) for item in completions] - if complete_action == "get-args": - if show_args: - return "\n".join(show_args) - elif complete_action == "is-args": - if show_args: - # Activate complete args (no files) - sys.exit(0) - else: - # Deactivate complete args (allow files) - sys.exit(1) - return "" # pragma: no cover - - -class PowerShellComplete(click.shell_completion.ShellComplete): - name = Shells.powershell.value - source_template = COMPLETION_SCRIPT_POWER_SHELL - - def source_vars(self) -> Dict[str, Any]: - return { - "complete_func": self.func_name, - "autocomplete_var": self.complete_var, - "prog_name": self.prog_name, - } - - def get_completion_args(self) -> Tuple[List[str], str]: - completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") - incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "") - cwords = click.parser.split_arg_string(completion_args) - args = cwords[1:] - return args, incomplete - - def format_completion(self, item: click.shell_completion.CompletionItem) -> str: - return f"{item.value}:::{item.help or ' '}" - - -def completion_init() -> None: - click.shell_completion.add_completion_class(BashComplete, Shells.bash.value) - click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value) - click.shell_completion.add_completion_class(FishComplete, Shells.fish.value) - click.shell_completion.add_completion_class( - PowerShellComplete, Shells.powershell.value - ) - click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/websockets/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/websockets/__init__.py deleted file mode 100644 index dcf3d81500912669ca3fae8f06acd3d3aad5d8ae..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/websockets/__init__.py +++ /dev/null @@ -1,114 +0,0 @@ -from __future__ import annotations - -from .imports import lazy_import -from .version import version as __version__ # noqa: F401 - - -__all__ = [ - "AbortHandshake", - "basic_auth_protocol_factory", - "BasicAuthWebSocketServerProtocol", - "broadcast", - "ClientProtocol", - "connect", - "ConnectionClosed", - "ConnectionClosedError", - "ConnectionClosedOK", - "Data", - "DuplicateParameter", - "ExtensionName", - "ExtensionParameter", - "InvalidHandshake", - "InvalidHeader", - "InvalidHeaderFormat", - "InvalidHeaderValue", - "InvalidMessage", - "InvalidOrigin", - "InvalidParameterName", - "InvalidParameterValue", - "InvalidState", - "InvalidStatus", - "InvalidStatusCode", - "InvalidUpgrade", - "InvalidURI", - "LoggerLike", - "NegotiationError", - "Origin", - "parse_uri", - "PayloadTooBig", - "ProtocolError", - "RedirectHandshake", - "SecurityError", - "serve", - "ServerProtocol", - "Subprotocol", - "unix_connect", - "unix_serve", - "WebSocketClientProtocol", - "WebSocketCommonProtocol", - "WebSocketException", - "WebSocketProtocolError", - "WebSocketServer", - "WebSocketServerProtocol", - "WebSocketURI", -] - -lazy_import( - globals(), - aliases={ - "auth": ".legacy", - "basic_auth_protocol_factory": ".legacy.auth", - "BasicAuthWebSocketServerProtocol": ".legacy.auth", - "broadcast": ".legacy.protocol", - "ClientProtocol": ".client", - "connect": ".legacy.client", - "unix_connect": ".legacy.client", - "WebSocketClientProtocol": ".legacy.client", - "Headers": ".datastructures", - "MultipleValuesError": ".datastructures", - "WebSocketException": ".exceptions", - "ConnectionClosed": ".exceptions", - "ConnectionClosedError": ".exceptions", - "ConnectionClosedOK": ".exceptions", - "InvalidHandshake": ".exceptions", - "SecurityError": ".exceptions", - "InvalidMessage": ".exceptions", - "InvalidHeader": ".exceptions", - "InvalidHeaderFormat": ".exceptions", - "InvalidHeaderValue": ".exceptions", - "InvalidOrigin": ".exceptions", - "InvalidUpgrade": ".exceptions", - "InvalidStatus": ".exceptions", - "InvalidStatusCode": ".exceptions", - "NegotiationError": ".exceptions", - "DuplicateParameter": ".exceptions", - "InvalidParameterName": ".exceptions", - "InvalidParameterValue": ".exceptions", - "AbortHandshake": ".exceptions", - "RedirectHandshake": ".exceptions", - "InvalidState": ".exceptions", - "InvalidURI": ".exceptions", - "PayloadTooBig": ".exceptions", - "ProtocolError": ".exceptions", - "WebSocketProtocolError": ".exceptions", - "protocol": ".legacy", - "WebSocketCommonProtocol": ".legacy.protocol", - "ServerProtocol": ".server", - "serve": ".legacy.server", - "unix_serve": ".legacy.server", - "WebSocketServerProtocol": ".legacy.server", - "WebSocketServer": ".legacy.server", - "Data": ".typing", - "LoggerLike": ".typing", - "Origin": ".typing", - "ExtensionHeader": ".typing", - "ExtensionParameter": ".typing", - "Subprotocol": ".typing", - }, - deprecated_aliases={ - "framing": ".legacy", - "handshake": ".legacy", - "parse_uri": ".uri", - "WebSocketURI": ".uri", - }, -) diff --git a/spaces/psychpsych/emilianJR-CyberRealistic_V3/README.md b/spaces/psychpsych/emilianJR-CyberRealistic_V3/README.md deleted file mode 100644 index 40375f4088bb52a771f2a7df33d30aef6cb8b989..0000000000000000000000000000000000000000 --- a/spaces/psychpsych/emilianJR-CyberRealistic_V3/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: EmilianJR-CyberRealistic V3 -emoji: 💻 -colorFrom: indigo -colorTo: blue -sdk: gradio -sdk_version: 3.33.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/pyInter/Liyuu_sovits4/cluster/__init__.py b/spaces/pyInter/Liyuu_sovits4/cluster/__init__.py deleted file mode 100644 index f1b9bde04e73e9218a5d534227caa4c25332f424..0000000000000000000000000000000000000000 --- a/spaces/pyInter/Liyuu_sovits4/cluster/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -import numpy as np -import torch -from sklearn.cluster import KMeans - -def get_cluster_model(ckpt_path): - checkpoint = torch.load(ckpt_path) - kmeans_dict = {} - for spk, ckpt in checkpoint.items(): - km = KMeans(ckpt["n_features_in_"]) - km.__dict__["n_features_in_"] = ckpt["n_features_in_"] - km.__dict__["_n_threads"] = ckpt["_n_threads"] - km.__dict__["cluster_centers_"] = ckpt["cluster_centers_"] - kmeans_dict[spk] = km - return kmeans_dict - -def get_cluster_result(model, x, speaker): - """ - x: np.array [t, 256] - return cluster class result - """ - return model[speaker].predict(x) - -def get_cluster_center_result(model, x,speaker): - """x: np.array [t, 256]""" - predict = model[speaker].predict(x) - return model[speaker].cluster_centers_[predict] - -def get_center(model, x,speaker): - return model[speaker].cluster_centers_[x] diff --git a/spaces/pycoming/bingo/src/components/ui/alert-dialog.tsx b/spaces/pycoming/bingo/src/components/ui/alert-dialog.tsx deleted file mode 100644 index 17fec4d16510328deacc1416569173c97761ef72..0000000000000000000000000000000000000000 --- a/spaces/pycoming/bingo/src/components/ui/alert-dialog.tsx +++ /dev/null @@ -1,150 +0,0 @@ -'use client' - -import * as React from 'react' -import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog' - -import { cn } from '@/lib/utils' -import { buttonVariants } from '@/components/ui/button' - -const AlertDialog = AlertDialogPrimitive.Root - -const AlertDialogTrigger = AlertDialogPrimitive.Trigger - -const AlertDialogPortal = ({ - className, - children, - ...props -}: AlertDialogPrimitive.AlertDialogPortalProps) => ( - -
    - {children} -
    -
    -) -AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName - -const AlertDialogOverlay = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - -)) -AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName - -const AlertDialogContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - - - - -)) -AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName - -const AlertDialogHeader = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
    -) -AlertDialogHeader.displayName = 'AlertDialogHeader' - -const AlertDialogFooter = ({ - className, - ...props -}: React.HTMLAttributes) => ( -
    -) -AlertDialogFooter.displayName = 'AlertDialogFooter' - -const AlertDialogTitle = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName - -const AlertDialogDescription = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogDescription.displayName = - AlertDialogPrimitive.Description.displayName - -const AlertDialogAction = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName - -const AlertDialogCancel = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName - -export { - AlertDialog, - AlertDialogTrigger, - AlertDialogContent, - AlertDialogHeader, - AlertDialogFooter, - AlertDialogTitle, - AlertDialogDescription, - AlertDialogAction, - AlertDialogCancel -} diff --git a/spaces/pyodide-demo/self-hosted/README.md b/spaces/pyodide-demo/self-hosted/README.md deleted file mode 100644 index ddde9f5294c6ac089dd60f26764a88cbd45e7b25..0000000000000000000000000000000000000000 --- a/spaces/pyodide-demo/self-hosted/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Self-hosted Pyodide -emoji: 🐍 -colorFrom: gray -colorTo: gray -sdk: static -app_file: console.html -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/pytorch/PGAN/README.md b/spaces/pytorch/PGAN/README.md deleted file mode 100644 index 17b5260642f4b31311c658f1bfa95c7520a71f90..0000000000000000000000000000000000000000 --- a/spaces/pytorch/PGAN/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: PGAN -emoji: 📈 -colorFrom: indigo -colorTo: red -sdk: gradio -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/qingxu98/gpt-academic/request_llm/bridge_newbing.py b/spaces/qingxu98/gpt-academic/request_llm/bridge_newbing.py deleted file mode 100644 index 2136f01beb3edd25b94dd8048c20b63a14ef905e..0000000000000000000000000000000000000000 --- a/spaces/qingxu98/gpt-academic/request_llm/bridge_newbing.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -======================================================================== -第一部分:来自EdgeGPT.py -https://github.com/acheong08/EdgeGPT -======================================================================== -""" -from .edge_gpt import NewbingChatbot -load_message = "等待NewBing响应。" - -""" -======================================================================== -第二部分:子进程Worker(调用主体) -======================================================================== -""" -import time -import json -import re -import logging -import asyncio -import importlib -import threading -from toolbox import update_ui, get_conf, trimmed_format_exc -from multiprocessing import Process, Pipe - -def preprocess_newbing_out(s): - pattern = r'\^(\d+)\^' # 匹配^数字^ - sub = lambda m: '('+m.group(1)+')' # 将匹配到的数字作为替换值 - result = re.sub(pattern, sub, s) # 替换操作 - if '[1]' in result: - result += '\n\n```reference\n' + "\n".join([r for r in result.split('\n') if r.startswith('[')]) + '\n```\n' - return result - -def preprocess_newbing_out_simple(result): - if '[1]' in result: - result += '\n\n```reference\n' + "\n".join([r for r in result.split('\n') if r.startswith('[')]) + '\n```\n' - return result - -class NewBingHandle(Process): - def __init__(self): - super().__init__(daemon=True) - self.parent, self.child = Pipe() - self.newbing_model = None - self.info = "" - self.success = True - self.local_history = [] - self.check_dependency() - self.start() - self.threadLock = threading.Lock() - - def check_dependency(self): - try: - self.success = False - import certifi, httpx, rich - self.info = "依赖检测通过,等待NewBing响应。注意目前不能多人同时调用NewBing接口(有线程锁),否则将导致每个人的NewBing问询历史互相渗透。调用NewBing时,会自动使用已配置的代理。" - self.success = True - except: - self.info = "缺少的依赖,如果要使用Newbing,除了基础的pip依赖以外,您还需要运行`pip install -r request_llm/requirements_newbing.txt`安装Newbing的依赖。" - self.success = False - - def ready(self): - return self.newbing_model is not None - - async def async_run(self): - # 读取配置 - NEWBING_STYLE, = get_conf('NEWBING_STYLE') - from request_llm.bridge_all import model_info - endpoint = model_info['newbing']['endpoint'] - while True: - # 等待 - kwargs = self.child.recv() - question=kwargs['query'] - history=kwargs['history'] - system_prompt=kwargs['system_prompt'] - - # 是否重置 - if len(self.local_history) > 0 and len(history)==0: - await self.newbing_model.reset() - self.local_history = [] - - # 开始问问题 - prompt = "" - if system_prompt not in self.local_history: - self.local_history.append(system_prompt) - prompt += system_prompt + '\n' - - # 追加历史 - for ab in history: - a, b = ab - if a not in self.local_history: - self.local_history.append(a) - prompt += a + '\n' - # if b not in self.local_history: - # self.local_history.append(b) - # prompt += b + '\n' - - # 问题 - prompt += question - self.local_history.append(question) - print('question:', prompt) - # 提交 - async for final, response in self.newbing_model.ask_stream( - prompt=question, - conversation_style=NEWBING_STYLE, # ["creative", "balanced", "precise"] - wss_link=endpoint, # "wss://sydney.bing.com/sydney/ChatHub" - ): - if not final: - print(response) - self.child.send(str(response)) - else: - print('-------- receive final ---------') - self.child.send('[Finish]') - # self.local_history.append(response) - - - def run(self): - """ - 这个函数运行在子进程 - """ - # 第一次运行,加载参数 - self.success = False - self.local_history = [] - if (self.newbing_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'] - # cookie - NEWBING_COOKIES, = get_conf('NEWBING_COOKIES') - try: - cookies = json.loads(NEWBING_COOKIES) - except: - self.success = False - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] 不能加载Newbing组件。NEWBING_COOKIES未填写或有格式错误。') - self.child.send('[Fail]') - self.child.send('[Finish]') - raise RuntimeError(f"不能加载Newbing组件。NEWBING_COOKIES未填写或有格式错误。") - - try: - self.newbing_model = NewbingChatbot(proxy=self.proxies_https, cookies=cookies) - except: - self.success = False - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] 不能加载Newbing组件。{tb_str}') - self.child.send('[Fail]') - self.child.send('[Finish]') - raise RuntimeError(f"不能加载Newbing组件。") - - 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] Newbing失败 {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() # 等待newbing回复的片段 - if res == '[Finish]': - break # 结束 - elif res == '[Fail]': - self.success = False - break - else: - yield res # newbing回复的片段 - self.threadLock.release() - - -""" -======================================================================== -第三部分:主进程统一调用函数接口 -======================================================================== -""" -global newbing_handle -newbing_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 newbing_handle - if (newbing_handle is None) or (not newbing_handle.success): - newbing_handle = NewBingHandle() - observe_window[0] = load_message + "\n\n" + newbing_handle.info - if not newbing_handle.success: - error = newbing_handle.info - newbing_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]: 等待NewBing响应中 ..." - for response in newbing_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]: 等待NewBing响应中 ...")) - - global newbing_handle - if (newbing_handle is None) or (not newbing_handle.success): - newbing_handle = NewBingHandle() - chatbot[-1] = (inputs, load_message + "\n\n" + newbing_handle.info) - yield from update_ui(chatbot=chatbot, history=[]) - if not newbing_handle.success: - newbing_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]: 等待NewBing响应中 ...") - response = "[Local Message]: 等待NewBing响应中 ..." - yield from update_ui(chatbot=chatbot, history=history, msg="NewBing响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - for response in newbing_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=system_prompt, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']): - chatbot[-1] = (inputs, preprocess_newbing_out(response)) - yield from update_ui(chatbot=chatbot, history=history, msg="NewBing响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - if response == "[Local Message]: 等待NewBing响应中 ...": response = "[Local Message]: NewBing响应异常,请刷新界面重试 ..." - 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/quidiaMuxgu/Expedit-SAM/Cd Rt4.5 Sw 8.31.md b/spaces/quidiaMuxgu/Expedit-SAM/Cd Rt4.5 Sw 8.31.md deleted file mode 100644 index df49ebda475a80dd35f95d774fe11e503126ec9e..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Cd Rt4.5 Sw 8.31.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Cd Rt4.5 Sw 8.31


    DOWNLOADhttps://geags.com/2uCqnR



    -
    -CONSEJOS DE CARA A ACTUALIZAR: Usar un CD de buena calidad. AVISO!: a menudo es necesario entrar en concesión para solucionar ... 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (indian Rape Videos 11) FREE.md b/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (indian Rape Videos 11) FREE.md deleted file mode 100644 index ba1e071186e7a13b47ca72efa9b9c9618491455b..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (indian Rape Videos 11) FREE.md +++ /dev/null @@ -1,8 +0,0 @@ - -

    the thought of what's happening to the innocent men who are buying the cottage gets me enraged. i can't think or focus on anything else. i heard about this story on the radio and i just burst out laughing. i couldn't help it. i know that there are many innocent men out there who are walking into the buildings because they want to invest their money and make it grow, and they don't know what these sick men are planning. i hope that some of these men will get strong enough to testify in court.

    -

    the final day of the #ilo16copenhagen summit on modern slavery kick-off "prisoners of justice" event was march 20, 2016. the prison industry emerged as a client and a player in the sex industry to the same extent as the airline industry emerges in the tobacco industry. a tough, superlative woman who began her career as a police officer and then rose through the ranks of the massachusetts state police, kilcullen was the only woman in a room of 180 who was born in ireland. “i almost felt like i was in the room with all the famous men in the room,” she said with a laugh.

    -

    HD Online Player (indian rape videos 11)


    Download Zip >>>>> https://geags.com/2uCrI6



    -

    we've seen the scourge of prostitution for a long time now. it's been around since antiquity, and it's been mentioned in the bible over and over again. but it was just recently that it became legalised. and then if you look at the images and the videos, you can see this is a thriving business that has been funded by the prostitution laws and the warehousing system.

    -

    with a slew of more than 30 firsts under her belt, the multi-time olympian would have been one of the busiest campaigners in the summer of 2016 had she not been forced to undergo major reconstructive surgery after being diagnosed with a rare form of cancer. one of the more inspiring, largely selfless olympic champions, she sees the fight for equality for the sex workers of new zealand as a battle she is still fighting, with the #metoo movement providing a powerful ally in the fight for the rights of all women. today, new zealand has one of the world's highest rates of female victims of sexual violence, and gainsborough acknowledges that the statistics are incredibly scary."

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (kamasutra 3d Movie In Hindi 2013 Dow) LINK.md b/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (kamasutra 3d Movie In Hindi 2013 Dow) LINK.md deleted file mode 100644 index 860441b63beb75630232555e9c65fa0375075418..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/HD Online Player (kamasutra 3d Movie In Hindi 2013 Dow) LINK.md +++ /dev/null @@ -1,6 +0,0 @@ -

    HD Online Player (kamasutra 3d movie in hindi 2013 dow)


    DOWNLOADhttps://geags.com/2uCs2S



    -
    - 3cee63e6c2
    -
    -
    -

    diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Hujan Darah Di Tanah Bambu Pdf 28.md b/spaces/quidiaMuxgu/Expedit-SAM/Hujan Darah Di Tanah Bambu Pdf 28.md deleted file mode 100644 index f8a050f06a0679b7d0acc41bcb1682af42576d60..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Hujan Darah Di Tanah Bambu Pdf 28.md +++ /dev/null @@ -1,10 +0,0 @@ -
    -

    arief prasetya, 072511482011 (2012) biofiltran felcra pada penerapan adr (alternative despute resolution) dalam upaya penegakan restorative justice (studi kasus kekerasan dalam rumah tangga (kdrt) di satuan reskrim polres tanah laut polda kalim. thesis thesis, universitas airlangga.

    -

    hujan darah di tanah bambu pdf 28


    Download Zip - https://geags.com/2uCrwA



    -

    arief prasetya, 072511482011 (2011) biofiltran felcra pada penerapan adr (alternative despute resolution) dalam upaya penegakan restorative justice (studi kasus kekerasan dalam rumah tangga (kdrt) di satuan reskrim polres tanah laut polda kalim. thesis thesis, universitas airlangga.

    -

    uhasi bamdi, 090114018701 (2017) akses literasi menyajikan kesan percaya diri yang tepat, pendidikan juga merupakan salah satu kisi kemanusiaan (identification of the role of percaya diri in a good self image). disertasi uah, terbitan april 2017

    -

    jangki sudaraka, 121314113805 (2018) hayati patinya mengkatkan nadih dispersed in bambus bedad pada pada atau hidup kadi berasaan, pada sabi bedad linduhan panjang dan bendalir, hati kedalat dari padak pada ungkin. (iexposition to the air gives a strong oxygen to the bambus bedad, and causes the diaphragm to turn and flaten, and alkalinity is appeared)lisensi isckon, terbitan april 2018

    -

    iksanto siswal, 131129013695 (2017) faktor penyebaran analisa anal aturan kosmos di indonesia (issa)-sebidetanji komunikasi dan kinesisi yang mendapat bantu tanah pada tanah persimpan dan tanah kedalat dan kemuncsin (overview and assessment of the application of the model of ecosystm (issa)-sebidetanji komunikasi dan kinesis dan ecology in indonesia (issa)-sebidetanji komunikasi dan kinesis dan ecology in indonesia) belajar di direktorat jendela kemajuan di dajumuluk, surabaya.

    -

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/r3gm/Advanced-RVC-Inference/infer.py b/spaces/r3gm/Advanced-RVC-Inference/infer.py deleted file mode 100644 index 9a40678751ebbe05d371e4d094ad711464d239dc..0000000000000000000000000000000000000000 --- a/spaces/r3gm/Advanced-RVC-Inference/infer.py +++ /dev/null @@ -1,942 +0,0 @@ -import torch, os, traceback, sys, warnings, shutil, numpy as np -import gradio as gr -import librosa -import asyncio -import rarfile -import edge_tts -import yt_dlp -import ffmpeg -import gdown -import subprocess -import wave -import soundfile as sf -from scipy.io import wavfile -from datetime import datetime -from urllib.parse import urlparse -from mega import Mega - -now_dir = os.getcwd() -tmp = os.path.join(now_dir, "TEMP") -shutil.rmtree(tmp, ignore_errors=True) -os.makedirs(tmp, exist_ok=True) -os.environ["TEMP"] = tmp -from lib.infer_pack.models import ( - SynthesizerTrnMs256NSFsid, - SynthesizerTrnMs256NSFsid_nono, - SynthesizerTrnMs768NSFsid, - SynthesizerTrnMs768NSFsid_nono, -) -from fairseq import checkpoint_utils -from vc_infer_pipeline import VC -from config import Config -config = Config() - -tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices()) -voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list] - -hubert_model = None - -f0method_mode = ["pm", "harvest", "crepe"] -f0method_info = "PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)" - -if os.path.isfile("rmvpe.pt"): - f0method_mode.insert(2, "rmvpe") - f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better), and Crepe effect is good but requires GPU (Default: PM)" - -def load_hubert(): - global hubert_model - models, _, _ = checkpoint_utils.load_model_ensemble_and_task( - ["hubert_base.pt"], - suffix="", - ) - hubert_model = models[0] - hubert_model = hubert_model.to(config.device) - if config.is_half: - hubert_model = hubert_model.half() - else: - hubert_model = hubert_model.float() - hubert_model.eval() - -load_hubert() - -weight_root = "weights" -index_root = "weights/index" -weights_model = [] -weights_index = [] -for _, _, model_files in os.walk(weight_root): - for file in model_files: - if file.endswith(".pth"): - weights_model.append(file) -for _, _, index_files in os.walk(index_root): - for file in index_files: - if file.endswith('.index') and "trained" not in file: - weights_index.append(os.path.join(index_root, file)) - -def check_models(): - weights_model = [] - weights_index = [] - for _, _, model_files in os.walk(weight_root): - for file in model_files: - if file.endswith(".pth"): - weights_model.append(file) - for _, _, index_files in os.walk(index_root): - for file in index_files: - if file.endswith('.index') and "trained" not in file: - weights_index.append(os.path.join(index_root, file)) - return ( - gr.Dropdown.update(choices=sorted(weights_model), value=weights_model[0]), - gr.Dropdown.update(choices=sorted(weights_index)) - ) - -def clean(): - return ( - gr.Dropdown.update(value=""), - gr.Slider.update(visible=False) - ) - -def vc_single( - sid, - vc_audio_mode, - input_audio_path, - input_upload_audio, - vocal_audio, - tts_text, - tts_voice, - f0_up_key, - f0_file, - f0_method, - file_index, - index_rate, - filter_radius, - resample_sr, - rms_mix_rate, - protect -): # spk_item, input_audio0, vc_transform0,f0_file,f0method0 - global tgt_sr, net_g, vc, hubert_model, version, cpt - try: - logs = [] - print(f"Converting...") - logs.append(f"Converting...") - yield "\n".join(logs), None - if vc_audio_mode == "Input path" or "Youtube" and input_audio_path != "": - audio, sr = librosa.load(input_audio_path, sr=16000, mono=True) - elif vc_audio_mode == "Upload audio": - selected_audio = input_upload_audio - if vocal_audio: - selected_audio = vocal_audio - elif input_upload_audio: - selected_audio = input_upload_audio - sampling_rate, audio = selected_audio - duration = audio.shape[0] / sampling_rate - 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) - elif vc_audio_mode == "TTS Audio": - 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) - input_audio_path = "tts.mp3" - f0_up_key = int(f0_up_key) - times = [0, 0, 0] - if hubert_model == None: - load_hubert() - if_f0 = cpt.get("f0", 1) - audio_opt = vc.pipeline( - hubert_model, - net_g, - sid, - audio, - input_audio_path, - times, - f0_up_key, - f0_method, - file_index, - # file_big_npy, - index_rate, - if_f0, - filter_radius, - tgt_sr, - resample_sr, - rms_mix_rate, - version, - protect, - f0_file=f0_file - ) - if resample_sr >= 16000 and tgt_sr != resample_sr: - tgt_sr = resample_sr - index_info = ( - "Using index:%s." % file_index - if os.path.exists(file_index) - else "Index not used." - ) - print("Success.\n %s\nTime:\n npy:%ss, f0:%ss, infer:%ss" % ( - index_info, - times[0], - times[1], - times[2], - )) - info = f"{index_info}\n[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s" - logs.append(info) - yield "\n".join(logs), (tgt_sr, audio_opt) - except: - info = traceback.format_exc() - print(info) - logs.append(info) - yield "\n".join(logs), None - -def get_vc(sid, to_return_protect0): - global n_spk, tgt_sr, net_g, vc, cpt, version, weights_index - if sid == "" or sid == []: - global hubert_model - if hubert_model is not None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的 - print("clean_empty_cache") - del net_g, n_spk, vc, hubert_model, tgt_sr # ,cpt - hubert_model = net_g = n_spk = vc = hubert_model = tgt_sr = None - if torch.cuda.is_available(): - torch.cuda.empty_cache() - ###楼下不这么折腾清理不干净 - if_f0 = cpt.get("f0", 1) - version = cpt.get("version", "v1") - if version == "v1": - if if_f0 == 1: - net_g = SynthesizerTrnMs256NSFsid( - *cpt["config"], is_half=config.is_half - ) - else: - net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) - elif version == "v2": - if if_f0 == 1: - net_g = SynthesizerTrnMs768NSFsid( - *cpt["config"], is_half=config.is_half - ) - else: - net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"]) - del net_g, cpt - if torch.cuda.is_available(): - torch.cuda.empty_cache() - cpt = None - return ( - gr.Slider.update(maximum=2333, visible=False), - gr.Slider.update(visible=True), - gr.Dropdown.update(choices=sorted(weights_index), value=""), - gr.Markdown.update(value="#
    No model selected") - ) - print(f"Loading {sid} model...") - selected_model = sid[:-4] - cpt = torch.load(os.path.join(weight_root, sid), map_location="cpu") - tgt_sr = cpt["config"][-1] - cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] - if_f0 = cpt.get("f0", 1) - if if_f0 == 0: - to_return_protect0 = { - "visible": False, - "value": 0.5, - "__type__": "update", - } - else: - to_return_protect0 = { - "visible": True, - "value": to_return_protect0, - "__type__": "update", - } - version = cpt.get("version", "v1") - if version == "v1": - if if_f0 == 1: - net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half) - else: - net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) - elif version == "v2": - if if_f0 == 1: - net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half) - else: - net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"]) - del net_g.enc_q - print(net_g.load_state_dict(cpt["weight"], strict=False)) - net_g.eval().to(config.device) - if config.is_half: - net_g = net_g.half() - else: - net_g = net_g.float() - vc = VC(tgt_sr, config) - n_spk = cpt["config"][-3] - weights_index = [] - for _, _, index_files in os.walk(index_root): - for file in index_files: - if file.endswith('.index') and "trained" not in file: - weights_index.append(os.path.join(index_root, file)) - if weights_index == []: - selected_index = gr.Dropdown.update(value="") - else: - selected_index = gr.Dropdown.update(value=weights_index[0]) - for index, model_index in enumerate(weights_index): - if selected_model in model_index: - selected_index = gr.Dropdown.update(value=weights_index[index]) - break - return ( - gr.Slider.update(maximum=n_spk, visible=True), - to_return_protect0, - selected_index, - gr.Markdown.update( - f'##
    {selected_model}\n'+ - f'###
    RVC {version} Model' - ) - ) - -def find_audio_files(folder_path, extensions): - audio_files = [] - for root, dirs, files in os.walk(folder_path): - for file in files: - if any(file.endswith(ext) for ext in extensions): - audio_files.append(file) - return audio_files - -def vc_multi( - spk_item, - vc_input, - vc_output, - vc_transform0, - f0method0, - file_index, - index_rate, - filter_radius, - resample_sr, - rms_mix_rate, - protect, -): - global tgt_sr, net_g, vc, hubert_model, version, cpt - logs = [] - logs.append("Converting...") - yield "\n".join(logs) - print() - try: - if os.path.exists(vc_input): - folder_path = vc_input - extensions = [".mp3", ".wav", ".flac", ".ogg"] - audio_files = find_audio_files(folder_path, extensions) - for index, file in enumerate(audio_files, start=1): - audio, sr = librosa.load(os.path.join(folder_path, file), sr=16000, mono=True) - input_audio_path = folder_path, file - f0_up_key = int(vc_transform0) - times = [0, 0, 0] - if hubert_model == None: - load_hubert() - if_f0 = cpt.get("f0", 1) - audio_opt = vc.pipeline( - hubert_model, - net_g, - spk_item, - audio, - input_audio_path, - times, - f0_up_key, - f0method0, - file_index, - index_rate, - if_f0, - filter_radius, - tgt_sr, - resample_sr, - rms_mix_rate, - version, - protect, - f0_file=None - ) - if resample_sr >= 16000 and tgt_sr != resample_sr: - tgt_sr = resample_sr - output_path = f"{os.path.join(vc_output, file)}" - os.makedirs(os.path.join(vc_output), exist_ok=True) - sf.write( - output_path, - audio_opt, - tgt_sr, - ) - info = f"{index} / {len(audio_files)} | {file}" - print(info) - logs.append(info) - yield "\n".join(logs) - else: - logs.append("Folder not found or path doesn't exist.") - yield "\n".join(logs) - except: - info = traceback.format_exc() - print(info) - logs.append(info) - yield "\n".join(logs) - -def download_audio(url, audio_provider): - logs = [] - os.makedirs("dl_audio", exist_ok=True) - if url == "": - logs.append("URL required!") - yield None, "\n".join(logs) - return None, "\n".join(logs) - if audio_provider == "Youtube": - logs.append("Downloading the audio...") - yield None, "\n".join(logs) - ydl_opts = { - 'noplaylist': True, - 'format': 'bestaudio/best', - 'postprocessors': [{ - 'key': 'FFmpegExtractAudio', - 'preferredcodec': 'wav', - }], - "outtmpl": 'result/dl_audio/audio', - } - audio_path = "result/dl_audio/audio.wav" - with yt_dlp.YoutubeDL(ydl_opts) as ydl: - ydl.download([url]) - logs.append("Download Complete.") - yield audio_path, "\n".join(logs) - -def cut_vocal_and_inst_yt(split_model): - logs = [] - logs.append("Starting the audio splitting process...") - yield "\n".join(logs), None, None, None - command = f"demucs --two-stems=vocals -n {split_model} result/dl_audio/audio.wav -o output" - result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True) - for line in result.stdout: - logs.append(line) - yield "\n".join(logs), None, None, None - print(result.stdout) - vocal = f"output/{split_model}/audio/vocals.wav" - inst = f"output/{split_model}/audio/no_vocals.wav" - logs.append("Audio splitting complete.") - yield "\n".join(logs), vocal, inst, vocal - -def cut_vocal_and_inst(split_model, audio_data): - logs = [] - vocal_path = "output/result/audio.wav" - os.makedirs("output/result", exist_ok=True) - wavfile.write(vocal_path, audio_data[0], audio_data[1]) - logs.append("Starting the audio splitting process...") - yield "\n".join(logs), None, None - command = f"demucs --two-stems=vocals -n {split_model} {vocal_path} -o output" - result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True) - for line in result.stdout: - logs.append(line) - yield "\n".join(logs), None, None - print(result.stdout) - vocal = f"output/{split_model}/audio/vocals.wav" - inst = f"output/{split_model}/audio/no_vocals.wav" - logs.append("Audio splitting complete.") - yield "\n".join(logs), vocal, inst - -def combine_vocal_and_inst(audio_data, vocal_volume, inst_volume, split_model): - os.makedirs("output/result", exist_ok=True) - vocal_path = "output/result/output.wav" - output_path = "output/result/combine.mp3" - inst_path = f"output/{split_model}/audio/no_vocals.wav" - wavfile.write(vocal_path, audio_data[0], audio_data[1]) - command = f'ffmpeg -y -i {inst_path} -i {vocal_path} -filter_complex [0:a]volume={inst_volume}[i];[1:a]volume={vocal_volume}[v];[i][v]amix=inputs=2:duration=longest[a] -map [a] -b:a 320k -c:a libmp3lame {output_path}' - result = subprocess.run(command.split(), stdout=subprocess.PIPE) - print(result.stdout.decode()) - return output_path - -def download_and_extract_models(urls): - logs = [] - os.makedirs("zips", exist_ok=True) - os.makedirs(os.path.join("zips", "extract"), exist_ok=True) - os.makedirs(os.path.join(weight_root), exist_ok=True) - os.makedirs(os.path.join(index_root), exist_ok=True) - for link in urls.splitlines(): - url = link.strip() - if not url: - raise gr.Error("URL Required!") - return "No URLs provided." - model_zip = urlparse(url).path.split('/')[-2] + '.zip' - model_zip_path = os.path.join('zips', model_zip) - logs.append(f"Downloading...") - yield "\n".join(logs) - if "drive.google.com" in url: - gdown.download(url, os.path.join("zips", "extract"), quiet=False) - elif "mega.nz" in url: - m = Mega() - m.download_url(url, 'zips') - else: - os.system(f"wget {url} -O {model_zip_path}") - logs.append(f"Extracting...") - yield "\n".join(logs) - for filename in os.listdir("zips"): - archived_file = os.path.join("zips", filename) - if filename.endswith(".zip"): - shutil.unpack_archive(archived_file, os.path.join("zips", "extract"), 'zip') - elif filename.endswith(".rar"): - with rarfile.RarFile(archived_file, 'r') as rar: - rar.extractall(os.path.join("zips", "extract")) - for _, dirs, files in os.walk(os.path.join("zips", "extract")): - logs.append(f"Searching Model and Index...") - yield "\n".join(logs) - model = False - index = False - if files: - for file in files: - if file.endswith(".pth"): - basename = file[:-4] - shutil.move(os.path.join("zips", "extract", file), os.path.join(weight_root, file)) - model = True - if file.endswith('.index') and "trained" not in file: - shutil.move(os.path.join("zips", "extract", file), os.path.join(index_root, file)) - index = True - else: - logs.append("No model in main folder.") - yield "\n".join(logs) - logs.append("Searching in subfolders...") - yield "\n".join(logs) - for sub_dir in dirs: - for _, _, sub_files in os.walk(os.path.join("zips", "extract", sub_dir)): - for file in sub_files: - if file.endswith(".pth"): - basename = file[:-4] - shutil.move(os.path.join("zips", "extract", sub_dir, file), os.path.join(weight_root, file)) - model = True - if file.endswith('.index') and "trained" not in file: - shutil.move(os.path.join("zips", "extract", sub_dir, file), os.path.join(index_root, file)) - index = True - shutil.rmtree(os.path.join("zips", "extract", sub_dir)) - if index is False: - logs.append("Model only file, no Index file detected.") - yield "\n".join(logs) - logs.append("Download Completed!") - yield "\n".join(logs) - logs.append("Successfully download all models! Refresh your model list to load the model") - yield "\n".join(logs) - -def use_microphone(microphone): - if microphone == True: - return gr.Audio.update(source="microphone") - else: - return gr.Audio.update(source="upload") - -def change_audio_mode(vc_audio_mode): - if vc_audio_mode == "Input path": - return ( - # Input & Upload - gr.Textbox.update(visible=True), - gr.Checkbox.update(visible=False), - gr.Audio.update(visible=False), - # Youtube - gr.Dropdown.update(visible=False), - gr.Textbox.update(visible=False), - gr.Textbox.update(visible=False), - gr.Button.update(visible=False), - # Splitter - gr.Dropdown.update(visible=True), - gr.Textbox.update(visible=True), - gr.Button.update(visible=True), - gr.Button.update(visible=False), - gr.Audio.update(visible=False), - gr.Audio.update(visible=True), - gr.Audio.update(visible=True), - gr.Slider.update(visible=True), - gr.Slider.update(visible=True), - gr.Audio.update(visible=True), - gr.Button.update(visible=True), - # TTS - gr.Textbox.update(visible=False), - gr.Dropdown.update(visible=False) - ) - elif vc_audio_mode == "Upload audio": - return ( - # Input & Upload - gr.Textbox.update(visible=False), - gr.Checkbox.update(visible=True), - gr.Audio.update(visible=True), - # Youtube - gr.Dropdown.update(visible=False), - gr.Textbox.update(visible=False), - gr.Textbox.update(visible=False), - gr.Button.update(visible=False), - # Splitter - gr.Dropdown.update(visible=True), - gr.Textbox.update(visible=True), - gr.Button.update(visible=False), - gr.Button.update(visible=True), - gr.Audio.update(visible=False), - gr.Audio.update(visible=True), - gr.Audio.update(visible=True), - gr.Slider.update(visible=True), - gr.Slider.update(visible=True), - gr.Audio.update(visible=True), - gr.Button.update(visible=True), - # TTS - gr.Textbox.update(visible=False), - gr.Dropdown.update(visible=False) - ) - elif vc_audio_mode == "Youtube": - return ( - # Input & Upload - gr.Textbox.update(visible=False), - gr.Checkbox.update(visible=False), - gr.Audio.update(visible=False), - # Youtube - gr.Dropdown.update(visible=True), - gr.Textbox.update(visible=True), - gr.Textbox.update(visible=True), - gr.Button.update(visible=True), - # Splitter - gr.Dropdown.update(visible=True), - gr.Textbox.update(visible=True), - gr.Button.update(visible=True), - gr.Button.update(visible=False), - gr.Audio.update(visible=True), - gr.Audio.update(visible=True), - gr.Audio.update(visible=True), - gr.Slider.update(visible=True), - gr.Slider.update(visible=True), - gr.Audio.update(visible=True), - gr.Button.update(visible=True), - # TTS - gr.Textbox.update(visible=False), - gr.Dropdown.update(visible=False) - ) - elif vc_audio_mode == "TTS Audio": - return ( - # Input & Upload - gr.Textbox.update(visible=False), - gr.Checkbox.update(visible=False), - gr.Audio.update(visible=False), - # Youtube - gr.Dropdown.update(visible=False), - gr.Textbox.update(visible=False), - gr.Textbox.update(visible=False), - gr.Button.update(visible=False), - # Splitter - gr.Dropdown.update(visible=False), - gr.Textbox.update(visible=False), - gr.Button.update(visible=False), - gr.Button.update(visible=False), - gr.Audio.update(visible=False), - gr.Audio.update(visible=False), - gr.Audio.update(visible=False), - gr.Slider.update(visible=False), - gr.Slider.update(visible=False), - gr.Audio.update(visible=False), - gr.Button.update(visible=False), - # TTS - gr.Textbox.update(visible=True), - gr.Dropdown.update(visible=True) - ) - -with gr.Blocks() as app: - gr.Markdown( - "#
    Advanced RVC Inference\n" - ) - with gr.Row(): - sid = gr.Dropdown( - label="Weight", - choices=sorted(weights_model), - ) - file_index = gr.Dropdown( - label="List of index file", - choices=sorted(weights_index), - interactive=True, - ) - spk_item = gr.Slider( - minimum=0, - maximum=2333, - step=1, - label="Speaker ID", - value=0, - visible=False, - interactive=True, - ) - refresh_model = gr.Button("Refresh model list", variant="primary") - clean_button = gr.Button("Clear Model from memory", variant="primary") - refresh_model.click( - fn=check_models, inputs=[], outputs=[sid, file_index] - ) - clean_button.click(fn=clean, inputs=[], outputs=[sid, spk_item]) - with gr.TabItem("Inference"): - selected_model = gr.Markdown(value="#
    No model selected") - with gr.Row(): - with gr.Column(): - vc_audio_mode = gr.Dropdown(label="Input voice", choices=["Input path", "Upload audio", "Youtube", "TTS Audio"], allow_custom_value=False, value="Upload audio") - # Input - vc_input = gr.Textbox(label="Input audio path", visible=False) - # Upload - vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True) - vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True) - # Youtube - vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)") - vc_link = gr.Textbox(label="Youtube URL", visible=False, info="Example: https://www.youtube.com/watch?v=Nc0sB1Bmf-A", placeholder="https://www.youtube.com/watch?v=...") - vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False) - vc_download_button = gr.Button("Download Audio", variant="primary", visible=False) - vc_audio_preview = gr.Audio(label="Downloaded Audio Preview", visible=False) - # TTS - tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False) - tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female") - # Splitter - vc_split_model = gr.Dropdown(label="Splitter Model", choices=["hdemucs_mmi", "htdemucs", "htdemucs_ft", "mdx", "mdx_q", "mdx_extra_q"], allow_custom_value=False, visible=True, value="htdemucs", info="Select the splitter model (Default: htdemucs)") - vc_split_log = gr.Textbox(label="Output Information", visible=True, interactive=False) - vc_split_yt = gr.Button("Split Audio", variant="primary", visible=False) - vc_split = gr.Button("Split Audio", variant="primary", visible=True) - vc_vocal_preview = gr.Audio(label="Vocal Preview", interactive=False, visible=True) - vc_inst_preview = gr.Audio(label="Instrumental Preview", interactive=False, visible=True) - with gr.Column(): - vc_transform0 = gr.Number( - label="Transpose", - info='Type "12" to change from male to female convertion or Type "-12" to change female to male convertion.', - value=0 - ) - f0method0 = gr.Radio( - label="Pitch extraction algorithm", - info=f0method_info, - choices=f0method_mode, - value="pm", - interactive=True, - ) - index_rate0 = gr.Slider( - minimum=0, - maximum=1, - label="Retrieval feature ratio", - value=0.7, - interactive=True, - ) - filter_radius0 = gr.Slider( - minimum=0, - maximum=7, - label="Apply Median Filtering", - info="The value represents the filter radius and can reduce breathiness.", - value=3, - step=1, - interactive=True, - ) - resample_sr0 = gr.Slider( - minimum=0, - maximum=48000, - label="Resample the output audio", - info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling", - value=0, - step=1, - interactive=True, - ) - rms_mix_rate0 = gr.Slider( - minimum=0, - maximum=1, - label="Volume Envelope", - info="Use the volume envelope of the input to replace or mix with the volume envelope of the output. The closer the ratio is to 1, the more the output envelope is used", - value=1, - interactive=True, - ) - protect0 = gr.Slider( - minimum=0, - maximum=0.5, - label="Voice Protection", - info="Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy", - value=0.5, - step=0.01, - interactive=True, - ) - f0_file0 = gr.File( - label="F0 curve file (Optional)", - info="One pitch per line, Replace the default F0 and pitch modulation" - ) - with gr.Column(): - vc_log = gr.Textbox(label="Output Information", interactive=False) - vc_output = gr.Audio(label="Output Audio", interactive=False) - vc_convert = gr.Button("Convert", variant="primary") - vc_vocal_volume = gr.Slider( - minimum=0, - maximum=10, - label="Vocal volume", - value=1, - interactive=True, - step=1, - info="Adjust vocal volume (Default: 1}", - visible=True - ) - vc_inst_volume = gr.Slider( - minimum=0, - maximum=10, - label="Instrument volume", - value=1, - interactive=True, - step=1, - info="Adjust instrument volume (Default: 1}", - visible=True - ) - vc_combined_output = gr.Audio(label="Output Combined Audio", visible=True) - vc_combine = gr.Button("Combine",variant="primary", visible=True) - vc_convert.click( - vc_single, - [ - spk_item, - vc_audio_mode, - vc_input, - vc_upload, - vc_vocal_preview, - tts_text, - tts_voice, - vc_transform0, - f0_file0, - f0method0, - file_index, - index_rate0, - filter_radius0, - resample_sr0, - rms_mix_rate0, - protect0, - ], - [vc_log, vc_output], - ) - vc_download_button.click( - fn=download_audio, - inputs=[vc_link, vc_download_audio], - outputs=[vc_audio_preview, vc_log_yt] - ) - vc_split_yt.click( - fn=cut_vocal_and_inst_yt, - inputs=[vc_split_model], - outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview, vc_input] - ) - vc_split.click( - fn=cut_vocal_and_inst, - inputs=[vc_split_model, vc_upload], - outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview] - ) - vc_combine.click( - fn=combine_vocal_and_inst, - inputs=[vc_output, vc_vocal_volume, vc_inst_volume, vc_split_model], - outputs=[vc_combined_output] - ) - vc_microphone_mode.change( - fn=use_microphone, - inputs=vc_microphone_mode, - outputs=vc_upload - ) - vc_audio_mode.change( - fn=change_audio_mode, - inputs=[vc_audio_mode], - outputs=[ - # Input & Upload - vc_input, - vc_microphone_mode, - vc_upload, - # Youtube - vc_download_audio, - vc_link, - vc_log_yt, - vc_download_button, - # Splitter - vc_split_model, - vc_split_log, - vc_split_yt, - vc_split, - vc_audio_preview, - vc_vocal_preview, - vc_inst_preview, - vc_vocal_volume, - vc_inst_volume, - vc_combined_output, - vc_combine, - # TTS - tts_text, - tts_voice - ] - ) - sid.change(fn=get_vc, inputs=[sid, protect0], outputs=[spk_item, protect0, file_index, selected_model]) - with gr.TabItem("Batch Inference"): - with gr.Row(): - with gr.Column(): - vc_input_bat = gr.Textbox(label="Input audio path (folder)", visible=True) - vc_output_bat = gr.Textbox(label="Output audio path (folder)", value="result/batch", visible=True) - with gr.Column(): - vc_transform0_bat = gr.Number( - label="Transpose", - info='Type "12" to change from male to female convertion or Type "-12" to change female to male convertion.', - value=0 - ) - f0method0_bat = gr.Radio( - label="Pitch extraction algorithm", - info=f0method_info, - choices=f0method_mode, - value="pm", - interactive=True, - ) - index_rate0_bat = gr.Slider( - minimum=0, - maximum=1, - label="Retrieval feature ratio", - value=0.7, - interactive=True, - ) - filter_radius0_bat = gr.Slider( - minimum=0, - maximum=7, - label="Apply Median Filtering", - info="The value represents the filter radius and can reduce breathiness.", - value=3, - step=1, - interactive=True, - ) - resample_sr0_bat = gr.Slider( - minimum=0, - maximum=48000, - label="Resample the output audio", - info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling", - value=0, - step=1, - interactive=True, - ) - rms_mix_rate0_bat = gr.Slider( - minimum=0, - maximum=1, - label="Volume Envelope", - info="Use the volume envelope of the input to replace or mix with the volume envelope of the output. The closer the ratio is to 1, the more the output envelope is used", - value=1, - interactive=True, - ) - protect0_bat = gr.Slider( - minimum=0, - maximum=0.5, - label="Voice Protection", - info="Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy", - value=0.5, - step=0.01, - interactive=True, - ) - with gr.Column(): - vc_log_bat = gr.Textbox(label="Output Information", interactive=False) - vc_convert_bat = gr.Button("Convert", variant="primary") - vc_convert_bat.click( - vc_multi, - [ - spk_item, - vc_input_bat, - vc_output_bat, - vc_transform0_bat, - f0method0_bat, - file_index, - index_rate0_bat, - filter_radius0_bat, - resample_sr0_bat, - rms_mix_rate0_bat, - protect0_bat, - ], - [vc_log_bat], - ) - with gr.TabItem("Model Downloader"): - gr.Markdown( - "#
    Model Downloader (Beta)\n"+ - "####
    To download multi link you have to put your link to the textbox and every link separated by space\n"+ - "####
    Support Direct Link, Mega, Google Drive, etc" - ) - with gr.Column(): - md_text = gr.Textbox(label="URL") - with gr.Row(): - md_download = gr.Button(label="Convert", variant="primary") - md_download_logs = gr.Textbox(label="Output information", interactive=False) - md_download.click( - fn=download_and_extract_models, - inputs=[md_text], - outputs=[md_download_logs] - ) - with gr.TabItem("Settings"): - gr.Markdown( - "#
    Settings\n"+ - "####
    Work in progress" - ) - app.queue(concurrency_count=1, max_size=50, api_open=config.api).launch(share=config.colab) \ No newline at end of file diff --git a/spaces/radames/UserControllableLT-Latent-Transformer/expansion/dataloader/seqlist.py b/spaces/radames/UserControllableLT-Latent-Transformer/expansion/dataloader/seqlist.py deleted file mode 100644 index 2e0e8bda391a7ddfd09b3268065dc02712bc7575..0000000000000000000000000000000000000000 --- a/spaces/radames/UserControllableLT-Latent-Transformer/expansion/dataloader/seqlist.py +++ /dev/null @@ -1,26 +0,0 @@ -import torch.utils.data as data - -from PIL import Image -import os -import os.path -import numpy as np -import glob - -IMG_EXTENSIONS = [ - '.jpg', '.JPG', '.jpeg', '.JPEG', - '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', -] - - -def is_image_file(filename): - return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) - -def dataloader(filepath): - - train = [img for img in sorted(glob.glob('%s/*'%filepath))] - - l0_train = train[:-1] - l1_train = train[1:] - - - return sorted(l0_train), sorted(l1_train), sorted(l0_train) diff --git a/spaces/ramkamal2000/voice-conversion-ddp/speaker_encoder/data_objects/__init__.py b/spaces/ramkamal2000/voice-conversion-ddp/speaker_encoder/data_objects/__init__.py deleted file mode 100644 index 030317a1d9a328d452bf29bc7a802e29629b1a42..0000000000000000000000000000000000000000 --- a/spaces/ramkamal2000/voice-conversion-ddp/speaker_encoder/data_objects/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDataset -from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDataLoader diff --git a/spaces/rayan-saleh/whisper2notion/server/node_modules/@types/node/process.d.ts b/spaces/rayan-saleh/whisper2notion/server/node_modules/@types/node/process.d.ts deleted file mode 100644 index 12148f911b207a631a78c58987f2dbaf7df93dc0..0000000000000000000000000000000000000000 --- a/spaces/rayan-saleh/whisper2notion/server/node_modules/@types/node/process.d.ts +++ /dev/null @@ -1,1482 +0,0 @@ -declare module 'process' { - import * as tty from 'node:tty'; - import { Worker } from 'node:worker_threads'; - global { - var process: NodeJS.Process; - namespace NodeJS { - // this namespace merge is here because these are specifically used - // as the type for process.stdin, process.stdout, and process.stderr. - // they can't live in tty.d.ts because we need to disambiguate the imported name. - interface ReadStream extends tty.ReadStream {} - interface WriteStream extends tty.WriteStream {} - interface MemoryUsageFn { - /** - * The `process.memoryUsage()` method iterate over each page to gather informations about memory - * usage which can be slow depending on the program memory allocations. - */ - (): MemoryUsage; - /** - * method returns an integer representing the Resident Set Size (RSS) in bytes. - */ - rss(): number; - } - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; - } - interface CpuUsage { - user: number; - system: number; - } - interface ProcessRelease { - name: string; - sourceUrl?: string | undefined; - headersUrl?: string | undefined; - libUrl?: string | undefined; - lts?: string | undefined; - } - interface ProcessVersions extends Dict { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; - type Architecture = 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x64'; - type Signals = - | 'SIGABRT' - | 'SIGALRM' - | 'SIGBUS' - | 'SIGCHLD' - | 'SIGCONT' - | 'SIGFPE' - | 'SIGHUP' - | 'SIGILL' - | 'SIGINT' - | 'SIGIO' - | 'SIGIOT' - | 'SIGKILL' - | 'SIGPIPE' - | 'SIGPOLL' - | 'SIGPROF' - | 'SIGPWR' - | 'SIGQUIT' - | 'SIGSEGV' - | 'SIGSTKFLT' - | 'SIGSTOP' - | 'SIGSYS' - | 'SIGTERM' - | 'SIGTRAP' - | 'SIGTSTP' - | 'SIGTTIN' - | 'SIGTTOU' - | 'SIGUNUSED' - | 'SIGURG' - | 'SIGUSR1' - | 'SIGUSR2' - | 'SIGVTALRM' - | 'SIGWINCH' - | 'SIGXCPU' - | 'SIGXFSZ' - | 'SIGBREAK' - | 'SIGLOST' - | 'SIGINFO'; - type UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'; - type MultipleResolveType = 'resolve' | 'reject'; - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; - /** - * Most of the time the unhandledRejection will be an Error, but this should not be relied upon - * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. - */ - type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: unknown, sendHandle: unknown) => void; - type SignalsListener = (signal: Signals) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; - type WorkerListener = (worker: Worker) => void; - interface Socket extends ReadWriteStream { - isTTY?: true | undefined; - } - // Alias for compatibility - interface ProcessEnv extends Dict { - /** - * Can be used to change the default timezone at runtime - */ - TZ?: string; - } - interface HRTime { - (time?: [number, number]): [number, number]; - bigint(): bigint; - } - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @default false - */ - reportOnSignal: boolean; - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - interface ResourceUsage { - fsRead: number; - fsWrite: number; - involuntaryContextSwitches: number; - ipcReceived: number; - ipcSent: number; - majorPageFault: number; - maxRSS: number; - minorPageFault: number; - sharedMemorySize: number; - signalsCount: number; - swappedOut: number; - systemCPUTime: number; - unsharedDataSize: number; - unsharedStackSize: number; - userCPUTime: number; - voluntaryContextSwitches: number; - } - interface EmitWarningOptions { - /** - * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. - * - * @default 'Warning' - */ - type?: string | undefined; - /** - * A unique identifier for the warning instance being emitted. - */ - code?: string | undefined; - /** - * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. - * - * @default process.emitWarning - */ - ctor?: Function | undefined; - /** - * Additional text to include with the error. - */ - detail?: string | undefined; - } - interface ProcessConfig { - readonly target_defaults: { - readonly cflags: any[]; - readonly default_configuration: string; - readonly defines: string[]; - readonly include_dirs: string[]; - readonly libraries: string[]; - }; - readonly variables: { - readonly clang: number; - readonly host_arch: string; - readonly node_install_npm: boolean; - readonly node_install_waf: boolean; - readonly node_prefix: string; - readonly node_shared_openssl: boolean; - readonly node_shared_v8: boolean; - readonly node_shared_zlib: boolean; - readonly node_use_dtrace: boolean; - readonly node_use_etw: boolean; - readonly node_use_openssl: boolean; - readonly target_arch: string; - readonly v8_no_strict_aliasing: number; - readonly v8_use_snapshot: boolean; - readonly visibility: string; - }; - } - interface Process extends EventEmitter { - /** - * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is - * a `Writable` stream. - * - * For example, to copy `process.stdin` to `process.stdout`: - * - * ```js - * import { stdin, stdout } from 'process'; - * - * stdin.pipe(stdout); - * ``` - * - * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. - */ - stdout: WriteStream & { - fd: 1; - }; - /** - * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is - * a `Writable` stream. - * - * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. - */ - stderr: WriteStream & { - fd: 2; - }; - /** - * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is - * a `Readable` stream. - * - * For details of how to read from `stdin` see `readable.read()`. - * - * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that - * is compatible with scripts written for Node.js prior to v0.10\. - * For more information see `Stream compatibility`. - * - * In "old" streams mode the `stdin` stream is paused by default, so one - * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. - */ - stdin: ReadStream & { - fd: 0; - }; - openStdin(): Socket; - /** - * The `process.argv` property returns an array containing the command-line - * arguments passed when the Node.js process was launched. The first element will - * be {@link execPath}. See `process.argv0` if access to the original value - * of `argv[0]` is needed. The second element will be the path to the JavaScript - * file being executed. The remaining elements will be any additional command-line - * arguments. - * - * For example, assuming the following script for `process-args.js`: - * - * ```js - * import { argv } from 'process'; - * - * // print process.argv - * argv.forEach((val, index) => { - * console.log(`${index}: ${val}`); - * }); - * ``` - * - * Launching the Node.js process as: - * - * ```console - * $ node process-args.js one two=three four - * ``` - * - * Would generate the output: - * - * ```text - * 0: /usr/local/bin/node - * 1: /Users/mjr/work/node/process-args.js - * 2: one - * 3: two=three - * 4: four - * ``` - * @since v0.1.27 - */ - argv: string[]; - /** - * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. - * - * ```console - * $ bash -c 'exec -a customArgv0 ./node' - * > process.argv[0] - * '/Volumes/code/external/node/out/Release/node' - * > process.argv0 - * 'customArgv0' - * ``` - * @since v6.4.0 - */ - argv0: string; - /** - * The `process.execArgv` property returns the set of Node.js-specific command-line - * options passed when the Node.js process was launched. These options do not - * appear in the array returned by the {@link argv} property, and do not - * include the Node.js executable, the name of the script, or any options following - * the script name. These options are useful in order to spawn child processes with - * the same execution environment as the parent. - * - * ```console - * $ node --harmony script.js --version - * ``` - * - * Results in `process.execArgv`: - * - * ```js - * ['--harmony'] - * ``` - * - * And `process.argv`: - * - * ```js - * ['/usr/local/bin/node', 'script.js', '--version'] - * ``` - * - * Refer to `Worker constructor` for the detailed behavior of worker - * threads with this property. - * @since v0.7.7 - */ - execArgv: string[]; - /** - * The `process.execPath` property returns the absolute pathname of the executable - * that started the Node.js process. Symbolic links, if any, are resolved. - * - * ```js - * '/usr/local/bin/node' - * ``` - * @since v0.1.100 - */ - execPath: string; - /** - * The `process.abort()` method causes the Node.js process to exit immediately and - * generate a core file. - * - * This feature is not available in `Worker` threads. - * @since v0.7.0 - */ - abort(): never; - /** - * The `process.chdir()` method changes the current working directory of the - * Node.js process or throws an exception if doing so fails (for instance, if - * the specified `directory` does not exist). - * - * ```js - * import { chdir, cwd } from 'process'; - * - * console.log(`Starting directory: ${cwd()}`); - * try { - * chdir('/tmp'); - * console.log(`New directory: ${cwd()}`); - * } catch (err) { - * console.error(`chdir: ${err}`); - * } - * ``` - * - * This feature is not available in `Worker` threads. - * @since v0.1.17 - */ - chdir(directory: string): void; - /** - * The `process.cwd()` method returns the current working directory of the Node.js - * process. - * - * ```js - * import { cwd } from 'process'; - * - * console.log(`Current directory: ${cwd()}`); - * ``` - * @since v0.1.8 - */ - cwd(): string; - /** - * The port used by the Node.js debugger when enabled. - * - * ```js - * import process from 'process'; - * - * process.debugPort = 5858; - * ``` - * @since v0.7.2 - */ - debugPort: number; - /** - * The `process.emitWarning()` method can be used to emit custom or application - * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. - * - * ```js - * import { emitWarning } from 'process'; - * - * // Emit a warning with a code and additional detail. - * emitWarning('Something happened!', { - * code: 'MY_WARNING', - * detail: 'This is some additional information' - * }); - * // Emits: - * // (node:56338) [MY_WARNING] Warning: Something happened! - * // This is some additional information - * ``` - * - * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. - * - * ```js - * import process from 'process'; - * - * process.on('warning', (warning) => { - * console.warn(warning.name); // 'Warning' - * console.warn(warning.message); // 'Something happened!' - * console.warn(warning.code); // 'MY_WARNING' - * console.warn(warning.stack); // Stack trace - * console.warn(warning.detail); // 'This is some additional information' - * }); - * ``` - * - * If `warning` is passed as an `Error` object, the `options` argument is ignored. - * @since v8.0.0 - * @param warning The warning to emit. - */ - emitWarning(warning: string | Error, ctor?: Function): void; - emitWarning(warning: string | Error, type?: string, ctor?: Function): void; - emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; - emitWarning(warning: string | Error, options?: EmitWarningOptions): void; - /** - * The `process.env` property returns an object containing the user environment. - * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). - * - * An example of this object looks like: - * - * ```js - * { - * TERM: 'xterm-256color', - * SHELL: '/usr/local/bin/bash', - * USER: 'maciej', - * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', - * PWD: '/Users/maciej', - * EDITOR: 'vim', - * SHLVL: '1', - * HOME: '/Users/maciej', - * LOGNAME: 'maciej', - * _: '/usr/local/bin/node' - * } - * ``` - * - * It is possible to modify this object, but such modifications will not be - * reflected outside the Node.js process, or (unless explicitly requested) - * to other `Worker` threads. - * In other words, the following example would not work: - * - * ```console - * $ node -e 'process.env.foo = "bar"' && echo $foo - * ``` - * - * While the following will: - * - * ```js - * import { env } from 'process'; - * - * env.foo = 'bar'; - * console.log(env.foo); - * ``` - * - * Assigning a property on `process.env` will implicitly convert the value - * to a string. **This behavior is deprecated.** Future versions of Node.js may - * throw an error when the value is not a string, number, or boolean. - * - * ```js - * import { env } from 'process'; - * - * env.test = null; - * console.log(env.test); - * // => 'null' - * env.test = undefined; - * console.log(env.test); - * // => 'undefined' - * ``` - * - * Use `delete` to delete a property from `process.env`. - * - * ```js - * import { env } from 'process'; - * - * env.TEST = 1; - * delete env.TEST; - * console.log(env.TEST); - * // => undefined - * ``` - * - * On Windows operating systems, environment variables are case-insensitive. - * - * ```js - * import { env } from 'process'; - * - * env.TEST = 1; - * console.log(env.test); - * // => 1 - * ``` - * - * Unless explicitly specified when creating a `Worker` instance, - * each `Worker` thread has its own copy of `process.env`, based on its - * parent thread’s `process.env`, or whatever was specified as the `env` option - * to the `Worker` constructor. Changes to `process.env` will not be visible - * across `Worker` threads, and only the main thread can make changes that - * are visible to the operating system or to native add-ons. - * @since v0.1.27 - */ - env: ProcessEnv; - /** - * The `process.exit()` method instructs Node.js to terminate the process - * synchronously with an exit status of `code`. If `code` is omitted, exit uses - * either the 'success' code `0` or the value of `process.exitCode` if it has been - * set. Node.js will not terminate until all the `'exit'` event listeners are - * called. - * - * To exit with a 'failure' code: - * - * ```js - * import { exit } from 'process'; - * - * exit(1); - * ``` - * - * The shell that executed Node.js should see the exit code as `1`. - * - * Calling `process.exit()` will force the process to exit as quickly as possible - * even if there are still asynchronous operations pending that have not yet - * completed fully, including I/O operations to `process.stdout` and`process.stderr`. - * - * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ - * _work pending_ in the event loop. The `process.exitCode` property can be set to - * tell the process which exit code to use when the process exits gracefully. - * - * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being - * truncated and lost: - * - * ```js - * import { exit } from 'process'; - * - * // This is an example of what *not* to do: - * if (someConditionNotMet()) { - * printUsageToStdout(); - * exit(1); - * } - * ``` - * - * The reason this is problematic is because writes to `process.stdout` in Node.js - * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js - * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. - * - * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding - * scheduling any additional work for the event loop: - * - * ```js - * import process from 'process'; - * - * // How to properly set the exit code while letting - * // the process exit gracefully. - * if (someConditionNotMet()) { - * printUsageToStdout(); - * process.exitCode = 1; - * } - * ``` - * - * If it is necessary to terminate the Node.js process due to an error condition, - * throwing an _uncaught_ error and allowing the process to terminate accordingly - * is safer than calling `process.exit()`. - * - * In `Worker` threads, this function stops the current thread rather - * than the current process. - * @since v0.1.13 - * @param [code=0] The exit code. - */ - exit(code?: number): never; - /** - * A number which will be the process exit code, when the process either - * exits gracefully, or is exited via {@link exit} without specifying - * a code. - * - * Specifying a code to {@link exit} will override any - * previous setting of `process.exitCode`. - * @since v0.11.8 - */ - exitCode?: number | undefined; - /** - * The `process.getgid()` method returns the numerical group identity of the - * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.getgid) { - * console.log(`Current gid: ${process.getgid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v0.1.31 - */ - getgid?: () => number; - /** - * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a - * numeric ID or a group name - * string. If a group name is specified, this method blocks while resolving the - * associated numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.getgid && process.setgid) { - * console.log(`Current gid: ${process.getgid()}`); - * try { - * process.setgid(501); - * console.log(`New gid: ${process.getgid()}`); - * } catch (err) { - * console.log(`Failed to set gid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v0.1.31 - * @param id The group name or ID - */ - setgid?: (id: number | string) => void; - /** - * The `process.getuid()` method returns the numeric user identity of the process. - * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.getuid) { - * console.log(`Current uid: ${process.getuid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v0.1.28 - */ - getuid?: () => number; - /** - * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a - * numeric ID or a username string. - * If a username is specified, the method blocks while resolving the associated - * numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.getuid && process.setuid) { - * console.log(`Current uid: ${process.getuid()}`); - * try { - * process.setuid(501); - * console.log(`New uid: ${process.getuid()}`); - * } catch (err) { - * console.log(`Failed to set uid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v0.1.28 - */ - setuid?: (id: number | string) => void; - /** - * The `process.geteuid()` method returns the numerical effective user identity of - * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.geteuid) { - * console.log(`Current uid: ${process.geteuid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v2.0.0 - */ - geteuid?: () => number; - /** - * The `process.seteuid()` method sets the effective user identity of the process. - * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username - * string. If a username is specified, the method blocks while resolving the - * associated numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.geteuid && process.seteuid) { - * console.log(`Current uid: ${process.geteuid()}`); - * try { - * process.seteuid(501); - * console.log(`New uid: ${process.geteuid()}`); - * } catch (err) { - * console.log(`Failed to set uid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v2.0.0 - * @param id A user name or ID - */ - seteuid?: (id: number | string) => void; - /** - * The `process.getegid()` method returns the numerical effective group identity - * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.getegid) { - * console.log(`Current gid: ${process.getegid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v2.0.0 - */ - getegid?: () => number; - /** - * The `process.setegid()` method sets the effective group identity of the process. - * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group - * name string. If a group name is specified, this method blocks while resolving - * the associated a numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.getegid && process.setegid) { - * console.log(`Current gid: ${process.getegid()}`); - * try { - * process.setegid(501); - * console.log(`New gid: ${process.getegid()}`); - * } catch (err) { - * console.log(`Failed to set gid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v2.0.0 - * @param id A group name or ID - */ - setegid?: (id: number | string) => void; - /** - * The `process.getgroups()` method returns an array with the supplementary group - * IDs. POSIX leaves it unspecified if the effective group ID is included but - * Node.js ensures it always is. - * - * ```js - * import process from 'process'; - * - * if (process.getgroups) { - * console.log(process.getgroups()); // [ 16, 21, 297 ] - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v0.9.4 - */ - getgroups?: () => number[]; - /** - * The `process.setgroups()` method sets the supplementary group IDs for the - * Node.js process. This is a privileged operation that requires the Node.js - * process to have `root` or the `CAP_SETGID` capability. - * - * The `groups` array can contain numeric group IDs, group names, or both. - * - * ```js - * import process from 'process'; - * - * if (process.getgroups && process.setgroups) { - * try { - * process.setgroups([501]); - * console.log(process.getgroups()); // new groups - * } catch (err) { - * console.log(`Failed to set groups: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v0.9.4 - */ - setgroups?: (groups: ReadonlyArray) => void; - /** - * The `process.setUncaughtExceptionCaptureCallback()` function sets a function - * that will be invoked when an uncaught exception occurs, which will receive the - * exception value itself as its first argument. - * - * If such a function is set, the `'uncaughtException'` event will - * not be emitted. If `--abort-on-uncaught-exception` was passed from the - * command line or set through `v8.setFlagsFromString()`, the process will - * not abort. Actions configured to take place on exceptions such as report - * generations will be affected too - * - * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this - * method with a non-`null` argument while another capture function is set will - * throw an error. - * - * Using this function is mutually exclusive with using the deprecated `domain` built-in module. - * @since v9.3.0 - */ - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - /** - * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. - * @since v9.3.0 - */ - hasUncaughtExceptionCaptureCallback(): boolean; - /** - * The `process.version` property contains the Node.js version string. - * - * ```js - * import { version } from 'process'; - * - * console.log(`Version: ${version}`); - * // Version: v14.8.0 - * ``` - * - * To get the version string without the prepended _v_, use`process.versions.node`. - * @since v0.1.3 - */ - readonly version: string; - /** - * The `process.versions` property returns an object listing the version strings of - * Node.js and its dependencies. `process.versions.modules` indicates the current - * ABI version, which is increased whenever a C++ API changes. Node.js will refuse - * to load modules that were compiled against a different module ABI version. - * - * ```js - * import { versions } from 'process'; - * - * console.log(versions); - * ``` - * - * Will generate an object similar to: - * - * ```console - * { node: '11.13.0', - * v8: '7.0.276.38-node.18', - * uv: '1.27.0', - * zlib: '1.2.11', - * brotli: '1.0.7', - * ares: '1.15.0', - * modules: '67', - * nghttp2: '1.34.0', - * napi: '4', - * llhttp: '1.1.1', - * openssl: '1.1.1b', - * cldr: '34.0', - * icu: '63.1', - * tz: '2018e', - * unicode: '11.0' } - * ``` - * @since v0.2.0 - */ - readonly versions: ProcessVersions; - /** - * The `process.config` property returns an `Object` containing the JavaScript - * representation of the configure options used to compile the current Node.js - * executable. This is the same as the `config.gypi` file that was produced when - * running the `./configure` script. - * - * An example of the possible output looks like: - * - * ```js - * { - * target_defaults: - * { cflags: [], - * default_configuration: 'Release', - * defines: [], - * include_dirs: [], - * libraries: [] }, - * variables: - * { - * host_arch: 'x64', - * napi_build_version: 5, - * node_install_npm: 'true', - * node_prefix: '', - * node_shared_cares: 'false', - * node_shared_http_parser: 'false', - * node_shared_libuv: 'false', - * node_shared_zlib: 'false', - * node_use_dtrace: 'false', - * node_use_openssl: 'true', - * node_shared_openssl: 'false', - * strict_aliasing: 'true', - * target_arch: 'x64', - * v8_use_snapshot: 1 - * } - * } - * ``` - * - * The `process.config` property is **not** read-only and there are existing - * modules in the ecosystem that are known to extend, modify, or entirely replace - * the value of `process.config`. - * - * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made - * read-only in a future release. - * @since v0.7.7 - */ - readonly config: ProcessConfig; - /** - * The `process.kill()` method sends the `signal` to the process identified by`pid`. - * - * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. - * - * This method will throw an error if the target `pid` does not exist. As a special - * case, a signal of `0` can be used to test for the existence of a process. - * Windows platforms will throw an error if the `pid` is used to kill a process - * group. - * - * Even though the name of this function is `process.kill()`, it is really just a - * signal sender, like the `kill` system call. The signal sent may do something - * other than kill the target process. - * - * ```js - * import process, { kill } from 'process'; - * - * process.on('SIGHUP', () => { - * console.log('Got SIGHUP signal.'); - * }); - * - * setTimeout(() => { - * console.log('Exiting.'); - * process.exit(0); - * }, 100); - * - * kill(process.pid, 'SIGHUP'); - * ``` - * - * When `SIGUSR1` is received by a Node.js process, Node.js will start the - * debugger. See `Signal Events`. - * @since v0.0.6 - * @param pid A process ID - * @param [signal='SIGTERM'] The signal to send, either as a string or number. - */ - kill(pid: number, signal?: string | number): true; - /** - * The `process.pid` property returns the PID of the process. - * - * ```js - * import { pid } from 'process'; - * - * console.log(`This process is pid ${pid}`); - * ``` - * @since v0.1.15 - */ - readonly pid: number; - /** - * The `process.ppid` property returns the PID of the parent of the - * current process. - * - * ```js - * import { ppid } from 'process'; - * - * console.log(`The parent process is pid ${ppid}`); - * ``` - * @since v9.2.0, v8.10.0, v6.13.0 - */ - readonly ppid: number; - /** - * The `process.title` property returns the current process title (i.e. returns - * the current value of `ps`). Assigning a new value to `process.title` modifies - * the current value of `ps`. - * - * When a new value is assigned, different platforms will impose different maximum - * length restrictions on the title. Usually such restrictions are quite limited. - * For instance, on Linux and macOS, `process.title` is limited to the size of the - * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 - * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) - * cases. - * - * Assigning a value to `process.title` might not result in an accurate label - * within process manager applications such as macOS Activity Monitor or Windows - * Services Manager. - * @since v0.1.104 - */ - title: string; - /** - * The operating system CPU architecture for which the Node.js binary was compiled. - * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. - * - * ```js - * import { arch } from 'process'; - * - * console.log(`This processor architecture is ${arch}`); - * ``` - * @since v0.5.0 - */ - readonly arch: Architecture; - /** - * The `process.platform` property returns a string identifying the operating - * system platform for which the Node.js binary was compiled. - * - * Currently possible values are: - * - * * `'aix'` - * * `'darwin'` - * * `'freebsd'` - * * `'linux'` - * * `'openbsd'` - * * `'sunos'` - * * `'win32'` - * - * ```js - * import { platform } from 'process'; - * - * console.log(`This platform is ${platform}`); - * ``` - * - * The value `'android'` may also be returned if the Node.js is built on the - * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). - * @since v0.1.16 - */ - readonly platform: Platform; - /** - * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at - * runtime, `require.main` may still refer to the original main module in - * modules that were required before the change occurred. Generally, it's - * safe to assume that the two refer to the same module. - * - * As with `require.main`, `process.mainModule` will be `undefined` if there - * is no entry script. - * @since v0.1.17 - * @deprecated Since v14.0.0 - Use `main` instead. - */ - mainModule?: Module | undefined; - memoryUsage: MemoryUsageFn; - /** - * The `process.cpuUsage()` method returns the user and system CPU time usage of - * the current process, in an object with properties `user` and `system`, whose - * values are microsecond values (millionth of a second). These values measure time - * spent in user and system code respectively, and may end up being greater than - * actual elapsed time if multiple CPU cores are performing work for this process. - * - * The result of a previous call to `process.cpuUsage()` can be passed as the - * argument to the function, to get a diff reading. - * - * ```js - * import { cpuUsage } from 'process'; - * - * const startUsage = cpuUsage(); - * // { user: 38579, system: 6986 } - * - * // spin the CPU for 500 milliseconds - * const now = Date.now(); - * while (Date.now() - now < 500); - * - * console.log(cpuUsage(startUsage)); - * // { user: 514883, system: 11226 } - * ``` - * @since v6.1.0 - * @param previousValue A previous return value from calling `process.cpuUsage()` - */ - cpuUsage(previousValue?: CpuUsage): CpuUsage; - /** - * `process.nextTick()` adds `callback` to the "next tick queue". This queue is - * fully drained after the current operation on the JavaScript stack runs to - * completion and before the event loop is allowed to continue. It's possible to - * create an infinite loop if one were to recursively call `process.nextTick()`. - * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. - * - * ```js - * import { nextTick } from 'process'; - * - * console.log('start'); - * nextTick(() => { - * console.log('nextTick callback'); - * }); - * console.log('scheduled'); - * // Output: - * // start - * // scheduled - * // nextTick callback - * ``` - * - * This is important when developing APIs in order to give users the opportunity - * to assign event handlers _after_ an object has been constructed but before any - * I/O has occurred: - * - * ```js - * import { nextTick } from 'process'; - * - * function MyThing(options) { - * this.setupOptions(options); - * - * nextTick(() => { - * this.startDoingStuff(); - * }); - * } - * - * const thing = new MyThing(); - * thing.getReadyForStuff(); - * - * // thing.startDoingStuff() gets called now, not before. - * ``` - * - * It is very important for APIs to be either 100% synchronous or 100% - * asynchronous. Consider this example: - * - * ```js - * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! - * function maybeSync(arg, cb) { - * if (arg) { - * cb(); - * return; - * } - * - * fs.stat('file', cb); - * } - * ``` - * - * This API is hazardous because in the following case: - * - * ```js - * const maybeTrue = Math.random() > 0.5; - * - * maybeSync(maybeTrue, () => { - * foo(); - * }); - * - * bar(); - * ``` - * - * It is not clear whether `foo()` or `bar()` will be called first. - * - * The following approach is much better: - * - * ```js - * import { nextTick } from 'process'; - * - * function definitelyAsync(arg, cb) { - * if (arg) { - * nextTick(cb); - * return; - * } - * - * fs.stat('file', cb); - * } - * ``` - * @since v0.1.26 - * @param args Additional arguments to pass when invoking the `callback` - */ - nextTick(callback: Function, ...args: any[]): void; - /** - * The `process.release` property returns an `Object` containing metadata related - * to the current release, including URLs for the source tarball and headers-only - * tarball. - * - * `process.release` contains the following properties: - * - * ```js - * { - * name: 'node', - * lts: 'Erbium', - * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', - * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', - * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' - * } - * ``` - * - * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be - * relied upon to exist. - * @since v3.0.0 - */ - readonly release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * `process.umask()` returns the Node.js process's file mode creation mask. Child - * processes inherit the mask from the parent process. - * @since v0.1.19 - * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * - * security vulnerability. There is no safe, cross-platform alternative API. - */ - umask(): number; - /** - * Can only be set if not in worker thread. - */ - umask(mask: string | number): number; - /** - * The `process.uptime()` method returns the number of seconds the current Node.js - * process has been running. - * - * The return value includes fractions of a second. Use `Math.floor()` to get whole - * seconds. - * @since v0.5.0 - */ - uptime(): number; - hrtime: HRTime; - /** - * If Node.js is spawned with an IPC channel, the `process.send()` method can be - * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. - * - * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. - * - * The message goes through serialization and parsing. The resulting message might - * not be the same as what is originally sent. - * @since v0.5.9 - * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: - */ - send?( - message: any, - sendHandle?: any, - options?: { - swallowErrors?: boolean | undefined; - }, - callback?: (error: Error | null) => void - ): boolean; - /** - * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the - * IPC channel to the parent process, allowing the child process to exit gracefully - * once there are no other connections keeping it alive. - * - * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. - * - * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. - * @since v0.7.2 - */ - disconnect(): void; - /** - * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC - * channel is connected and will return `false` after`process.disconnect()` is called. - * - * Once `process.connected` is `false`, it is no longer possible to send messages - * over the IPC channel using `process.send()`. - * @since v0.7.2 - */ - connected: boolean; - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. - * - * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag - * representations. `process.allowedNodeEnvironmentFlags.has()` will - * return `true` in the following cases: - * - * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. - * * Flags passed through to V8 (as listed in `--v8-options`) may replace - * one or more _non-leading_ dashes for an underscore, or vice-versa; - * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, - * etc. - * * Flags may contain one or more equals (`=`) characters; all - * characters after and including the first equals will be ignored; - * e.g., `--stack-trace-limit=100`. - * * Flags _must_ be allowable within `NODE_OPTIONS`. - * - * When iterating over `process.allowedNodeEnvironmentFlags`, flags will - * appear only _once_; each will begin with one or more dashes. Flags - * passed through to V8 will contain underscores instead of non-leading - * dashes: - * - * ```js - * import { allowedNodeEnvironmentFlags } from 'process'; - * - * allowedNodeEnvironmentFlags.forEach((flag) => { - * // -r - * // --inspect-brk - * // --abort_on_uncaught_exception - * // ... - * }); - * ``` - * - * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail - * silently. - * - * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will - * contain what _would have_ been allowable. - * @since v10.10.0 - */ - allowedNodeEnvironmentFlags: ReadonlySet; - /** - * `process.report` is an object whose methods are used to generate diagnostic - * reports for the current process. Additional documentation is available in the `report documentation`. - * @since v11.8.0 - */ - report?: ProcessReport | undefined; - /** - * ```js - * import { resourceUsage } from 'process'; - * - * console.log(resourceUsage()); - * /* - * Will output: - * { - * userCPUTime: 82872, - * systemCPUTime: 4143, - * maxRSS: 33164, - * sharedMemorySize: 0, - * unsharedDataSize: 0, - * unsharedStackSize: 0, - * minorPageFault: 2469, - * majorPageFault: 0, - * swappedOut: 0, - * fsRead: 0, - * fsWrite: 8, - * ipcSent: 0, - * ipcReceived: 0, - * signalsCount: 0, - * voluntaryContextSwitches: 79, - * involuntaryContextSwitches: 1 - * } - * - * ``` - * @since v12.6.0 - * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. - */ - resourceUsage(): ResourceUsage; - /** - * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the - * documentation for the `'warning' event` and the `emitWarning() method` for more information about this - * flag's behavior. - * @since v0.8.0 - */ - traceDeprecation: boolean; - /* EventEmitter */ - addListener(event: 'beforeExit', listener: BeforeExitListener): this; - addListener(event: 'disconnect', listener: DisconnectListener): this; - addListener(event: 'exit', listener: ExitListener): this; - addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; - addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; - addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; - addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; - addListener(event: 'warning', listener: WarningListener): this; - addListener(event: 'message', listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; - addListener(event: 'worker', listener: WorkerListener): this; - emit(event: 'beforeExit', code: number): boolean; - emit(event: 'disconnect'): boolean; - emit(event: 'exit', code: number): boolean; - emit(event: 'rejectionHandled', promise: Promise): boolean; - emit(event: 'uncaughtException', error: Error): boolean; - emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; - emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; - emit(event: 'warning', warning: Error): boolean; - emit(event: 'message', message: unknown, sendHandle: unknown): this; - emit(event: Signals, signal?: Signals): boolean; - emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; - emit(event: 'worker', listener: WorkerListener): this; - on(event: 'beforeExit', listener: BeforeExitListener): this; - on(event: 'disconnect', listener: DisconnectListener): this; - on(event: 'exit', listener: ExitListener): this; - on(event: 'rejectionHandled', listener: RejectionHandledListener): this; - on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; - on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; - on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; - on(event: 'warning', listener: WarningListener): this; - on(event: 'message', listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: 'multipleResolves', listener: MultipleResolveListener): this; - on(event: 'worker', listener: WorkerListener): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: 'beforeExit', listener: BeforeExitListener): this; - once(event: 'disconnect', listener: DisconnectListener): this; - once(event: 'exit', listener: ExitListener): this; - once(event: 'rejectionHandled', listener: RejectionHandledListener): this; - once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; - once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; - once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; - once(event: 'warning', listener: WarningListener): this; - once(event: 'message', listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: 'multipleResolves', listener: MultipleResolveListener): this; - once(event: 'worker', listener: WorkerListener): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: 'beforeExit', listener: BeforeExitListener): this; - prependListener(event: 'disconnect', listener: DisconnectListener): this; - prependListener(event: 'exit', listener: ExitListener): this; - prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; - prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; - prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; - prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; - prependListener(event: 'warning', listener: WarningListener): this; - prependListener(event: 'message', listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; - prependListener(event: 'worker', listener: WorkerListener): this; - prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; - prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; - prependOnceListener(event: 'exit', listener: ExitListener): this; - prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; - prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; - prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; - prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; - prependOnceListener(event: 'warning', listener: WarningListener): this; - prependOnceListener(event: 'message', listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; - prependOnceListener(event: 'worker', listener: WorkerListener): this; - listeners(event: 'beforeExit'): BeforeExitListener[]; - listeners(event: 'disconnect'): DisconnectListener[]; - listeners(event: 'exit'): ExitListener[]; - listeners(event: 'rejectionHandled'): RejectionHandledListener[]; - listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; - listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; - listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; - listeners(event: 'warning'): WarningListener[]; - listeners(event: 'message'): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: 'multipleResolves'): MultipleResolveListener[]; - listeners(event: 'worker'): WorkerListener[]; - } - } - } - export = process; -} -declare module 'node:process' { - import process = require('process'); - export = process; -} diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Cubase 5 Mac Dmg Torrent.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Cubase 5 Mac Dmg Torrent.md deleted file mode 100644 index 90a19fa715be558749ef245b085302ef25515c0e..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Cubase 5 Mac Dmg Torrent.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Cubase 5 Mac Dmg Torrent


    Download Ziphttps://urlgoal.com/2uCJvQ



    - -Cubase 6.5 Mac Crack Torrent ->>->>->> http://cinurl.com/11425w. ... Cubase,Studio,5,Torrent,win7,enterprise,64bit,ie9,corel,draw,for,mac,free,download,how ... 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/DVDFab Downloader 2.1.0.3 Crack Keygen 2020.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/DVDFab Downloader 2.1.0.3 Crack Keygen 2020.md deleted file mode 100644 index a045bb41f568b777b73af73cab51bed50bfec9d4..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/DVDFab Downloader 2.1.0.3 Crack Keygen 2020.md +++ /dev/null @@ -1,8 +0,0 @@ -
    -

    DVDFab can add a wide variety of video files, including movies, TV shows, trailers, and music clips. DVDFab Crack provides several media splitter and joiner feature. To cut data, add effects to video files, and adjust the playback speed, you will have a wide range of options to perform the assigned task. And, DVDFab is a multi-format disc burner and a multi-format DVD/CD/Blu-ray writer.

    -

    To copy the discs, DVDFab allows you to copy multiple discs at the same time. When you copy the discs, you can copy content from the original disc to another one. Additionally, you can copy content from one disc to the other one. Moreover, you can download the latest version of DVDFab 12.0.9.2 Crack torrent or a serial key, registration key, instant or direct key or a registration code. It is an encoder, DVD burner, and disc menu generator for creating DVDs.

    -

    DVDFab Downloader 2.1.0.3 Crack Keygen 2020


    Download ——— https://urlgoal.com/2uCJhw



    -

    If you want to read DVD into a computer, you can use DVDFab DVD Burner to do it. DVDFab can even copy DVD files to other computers and smartphones. DVDFab DVD Copy is a large collection of useful features. It can make an ISO copy of the disc, burn it on a blank disc, and complete the disc burning. It is one of the most useful DVD tools. Moreover, DVDFab allows you to import and burn the DVD. This creates a typical data copy format of the DVD.

    -

    In DVDFab Crack, you can copy movies to hard drives and hard drives. Also, it can extract videos and other files from Blu-ray and DVD discs in the compatible structure. One of the functions of DVDFab Crack is to arrange images. There are over a thousand images in the DVDFab 11.4 Torrent. What is more, it allows you to add numerous effects. To be specific, the program includes all the main features in one, and so does DVDFab 11.7 Crack. The program includes all the main features in one, and so does DVDFab 11.7 Crack. DVDFab has a fast encoding speed, and so does DVDFab 11.7 Crack. The speed of DVD copying can be adjusted as required. You can manage and use the Copy status. The application can import an image file into the editor.

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/core/bbox/coder/delta_xywh_bbox_coder.py b/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/core/bbox/coder/delta_xywh_bbox_coder.py deleted file mode 100644 index a7f1c62fa7bde9280f9edcb4926cd77bfdd3a0b4..0000000000000000000000000000000000000000 --- a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/core/bbox/coder/delta_xywh_bbox_coder.py +++ /dev/null @@ -1,392 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import warnings - -import mmcv -import numpy as np -import torch - -from ..builder import BBOX_CODERS -from .base_bbox_coder import BaseBBoxCoder - - -@BBOX_CODERS.register_module() -class DeltaXYWHBBoxCoder(BaseBBoxCoder): - """Delta XYWH BBox coder. - - Following the practice in `R-CNN `_, - this coder encodes bbox (x1, y1, x2, y2) into delta (dx, dy, dw, dh) and - decodes delta (dx, dy, dw, dh) back to original bbox (x1, y1, x2, y2). - - Args: - target_means (Sequence[float]): Denormalizing means of target for - delta coordinates - target_stds (Sequence[float]): Denormalizing standard deviation of - target for delta coordinates - clip_border (bool, optional): Whether clip the objects outside the - border of the image. Defaults to True. - add_ctr_clamp (bool): Whether to add center clamp, when added, the - predicted box is clamped is its center is too far away from - the original anchor's center. Only used by YOLOF. Default False. - ctr_clamp (int): the maximum pixel shift to clamp. Only used by YOLOF. - Default 32. - """ - - def __init__(self, - target_means=(0., 0., 0., 0.), - target_stds=(1., 1., 1., 1.), - clip_border=True, - add_ctr_clamp=False, - ctr_clamp=32): - super(BaseBBoxCoder, self).__init__() - self.means = target_means - self.stds = target_stds - self.clip_border = clip_border - self.add_ctr_clamp = add_ctr_clamp - self.ctr_clamp = ctr_clamp - - def encode(self, bboxes, gt_bboxes): - """Get box regression transformation deltas that can be used to - transform the ``bboxes`` into the ``gt_bboxes``. - - Args: - bboxes (torch.Tensor): Source boxes, e.g., object proposals. - gt_bboxes (torch.Tensor): Target of the transformation, e.g., - ground-truth boxes. - - Returns: - torch.Tensor: Box transformation deltas - """ - - assert bboxes.size(0) == gt_bboxes.size(0) - assert bboxes.size(-1) == gt_bboxes.size(-1) == 4 - encoded_bboxes = bbox2delta(bboxes, gt_bboxes, self.means, self.stds) - return encoded_bboxes - - def decode(self, - bboxes, - pred_bboxes, - max_shape=None, - wh_ratio_clip=16 / 1000): - """Apply transformation `pred_bboxes` to `boxes`. - - Args: - bboxes (torch.Tensor): Basic boxes. Shape (B, N, 4) or (N, 4) - pred_bboxes (Tensor): Encoded offsets with respect to each roi. - Has shape (B, N, num_classes * 4) or (B, N, 4) or - (N, num_classes * 4) or (N, 4). Note N = num_anchors * W * H - when rois is a grid of anchors.Offset encoding follows [1]_. - max_shape (Sequence[int] or torch.Tensor or Sequence[ - Sequence[int]],optional): Maximum bounds for boxes, specifies - (H, W, C) or (H, W). If bboxes shape is (B, N, 4), then - the max_shape should be a Sequence[Sequence[int]] - and the length of max_shape should also be B. - wh_ratio_clip (float, optional): The allowed ratio between - width and height. - - Returns: - torch.Tensor: Decoded boxes. - """ - - assert pred_bboxes.size(0) == bboxes.size(0) - if pred_bboxes.ndim == 3: - assert pred_bboxes.size(1) == bboxes.size(1) - - if pred_bboxes.ndim == 2 and not torch.onnx.is_in_onnx_export(): - # single image decode - decoded_bboxes = delta2bbox(bboxes, pred_bboxes, self.means, - self.stds, max_shape, wh_ratio_clip, - self.clip_border, self.add_ctr_clamp, - self.ctr_clamp) - else: - if pred_bboxes.ndim == 3 and not torch.onnx.is_in_onnx_export(): - warnings.warn( - 'DeprecationWarning: onnx_delta2bbox is deprecated ' - 'in the case of batch decoding and non-ONNX, ' - 'please use “delta2bbox” instead. In order to improve ' - 'the decoding speed, the batch function will no ' - 'longer be supported. ') - decoded_bboxes = onnx_delta2bbox(bboxes, pred_bboxes, self.means, - self.stds, max_shape, - wh_ratio_clip, self.clip_border, - self.add_ctr_clamp, - self.ctr_clamp) - - return decoded_bboxes - - -@mmcv.jit(coderize=True) -def bbox2delta(proposals, gt, means=(0., 0., 0., 0.), stds=(1., 1., 1., 1.)): - """Compute deltas of proposals w.r.t. gt. - - We usually compute the deltas of x, y, w, h of proposals w.r.t ground - truth bboxes to get regression target. - This is the inverse function of :func:`delta2bbox`. - - Args: - proposals (Tensor): Boxes to be transformed, shape (N, ..., 4) - gt (Tensor): Gt bboxes to be used as base, shape (N, ..., 4) - means (Sequence[float]): Denormalizing means for delta coordinates - stds (Sequence[float]): Denormalizing standard deviation for delta - coordinates - - Returns: - Tensor: deltas with shape (N, 4), where columns represent dx, dy, - dw, dh. - """ - assert proposals.size() == gt.size() - - proposals = proposals.float() - gt = gt.float() - px = (proposals[..., 0] + proposals[..., 2]) * 0.5 - py = (proposals[..., 1] + proposals[..., 3]) * 0.5 - pw = proposals[..., 2] - proposals[..., 0] - ph = proposals[..., 3] - proposals[..., 1] - - gx = (gt[..., 0] + gt[..., 2]) * 0.5 - gy = (gt[..., 1] + gt[..., 3]) * 0.5 - gw = gt[..., 2] - gt[..., 0] - gh = gt[..., 3] - gt[..., 1] - - dx = (gx - px) / pw - dy = (gy - py) / ph - dw = torch.log(gw / pw) - dh = torch.log(gh / ph) - deltas = torch.stack([dx, dy, dw, dh], dim=-1) - - means = deltas.new_tensor(means).unsqueeze(0) - stds = deltas.new_tensor(stds).unsqueeze(0) - deltas = deltas.sub_(means).div_(stds) - - return deltas - - -@mmcv.jit(coderize=True) -def delta2bbox(rois, - deltas, - means=(0., 0., 0., 0.), - stds=(1., 1., 1., 1.), - max_shape=None, - wh_ratio_clip=16 / 1000, - clip_border=True, - add_ctr_clamp=False, - ctr_clamp=32): - """Apply deltas to shift/scale base boxes. - - Typically the rois are anchor or proposed bounding boxes and the deltas are - network outputs used to shift/scale those boxes. - This is the inverse function of :func:`bbox2delta`. - - Args: - rois (Tensor): Boxes to be transformed. Has shape (N, 4). - deltas (Tensor): Encoded offsets relative to each roi. - Has shape (N, num_classes * 4) or (N, 4). Note - N = num_base_anchors * W * H, when rois is a grid of - anchors. Offset encoding follows [1]_. - means (Sequence[float]): Denormalizing means for delta coordinates. - Default (0., 0., 0., 0.). - stds (Sequence[float]): Denormalizing standard deviation for delta - coordinates. Default (1., 1., 1., 1.). - max_shape (tuple[int, int]): Maximum bounds for boxes, specifies - (H, W). Default None. - wh_ratio_clip (float): Maximum aspect ratio for boxes. Default - 16 / 1000. - clip_border (bool, optional): Whether clip the objects outside the - border of the image. Default True. - add_ctr_clamp (bool): Whether to add center clamp. When set to True, - the center of the prediction bounding box will be clamped to - avoid being too far away from the center of the anchor. - Only used by YOLOF. Default False. - ctr_clamp (int): the maximum pixel shift to clamp. Only used by YOLOF. - Default 32. - - Returns: - Tensor: Boxes with shape (N, num_classes * 4) or (N, 4), where 4 - represent tl_x, tl_y, br_x, br_y. - - References: - .. [1] https://arxiv.org/abs/1311.2524 - - Example: - >>> rois = torch.Tensor([[ 0., 0., 1., 1.], - >>> [ 0., 0., 1., 1.], - >>> [ 0., 0., 1., 1.], - >>> [ 5., 5., 5., 5.]]) - >>> deltas = torch.Tensor([[ 0., 0., 0., 0.], - >>> [ 1., 1., 1., 1.], - >>> [ 0., 0., 2., -1.], - >>> [ 0.7, -1.9, -0.5, 0.3]]) - >>> delta2bbox(rois, deltas, max_shape=(32, 32, 3)) - tensor([[0.0000, 0.0000, 1.0000, 1.0000], - [0.1409, 0.1409, 2.8591, 2.8591], - [0.0000, 0.3161, 4.1945, 0.6839], - [5.0000, 5.0000, 5.0000, 5.0000]]) - """ - num_bboxes, num_classes = deltas.size(0), deltas.size(1) // 4 - if num_bboxes == 0: - return deltas - - deltas = deltas.reshape(-1, 4) - - means = deltas.new_tensor(means).view(1, -1) - stds = deltas.new_tensor(stds).view(1, -1) - denorm_deltas = deltas * stds + means - - dxy = denorm_deltas[:, :2] - dwh = denorm_deltas[:, 2:] - - # Compute width/height of each roi - rois_ = rois.repeat(1, num_classes).reshape(-1, 4) - pxy = ((rois_[:, :2] + rois_[:, 2:]) * 0.5) - pwh = (rois_[:, 2:] - rois_[:, :2]) - - dxy_wh = pwh * dxy - - max_ratio = np.abs(np.log(wh_ratio_clip)) - if add_ctr_clamp: - dxy_wh = torch.clamp(dxy_wh, max=ctr_clamp, min=-ctr_clamp) - dwh = torch.clamp(dwh, max=max_ratio) - else: - dwh = dwh.clamp(min=-max_ratio, max=max_ratio) - - gxy = pxy + dxy_wh - gwh = pwh * dwh.exp() - x1y1 = gxy - (gwh * 0.5) - x2y2 = gxy + (gwh * 0.5) - bboxes = torch.cat([x1y1, x2y2], dim=-1) - if clip_border and max_shape is not None: - bboxes[..., 0::2].clamp_(min=0, max=max_shape[1]) - bboxes[..., 1::2].clamp_(min=0, max=max_shape[0]) - bboxes = bboxes.reshape(num_bboxes, -1) - return bboxes - - -def onnx_delta2bbox(rois, - deltas, - means=(0., 0., 0., 0.), - stds=(1., 1., 1., 1.), - max_shape=None, - wh_ratio_clip=16 / 1000, - clip_border=True, - add_ctr_clamp=False, - ctr_clamp=32): - """Apply deltas to shift/scale base boxes. - - Typically the rois are anchor or proposed bounding boxes and the deltas are - network outputs used to shift/scale those boxes. - This is the inverse function of :func:`bbox2delta`. - - Args: - rois (Tensor): Boxes to be transformed. Has shape (N, 4) or (B, N, 4) - deltas (Tensor): Encoded offsets with respect to each roi. - Has shape (B, N, num_classes * 4) or (B, N, 4) or - (N, num_classes * 4) or (N, 4). Note N = num_anchors * W * H - when rois is a grid of anchors.Offset encoding follows [1]_. - means (Sequence[float]): Denormalizing means for delta coordinates. - Default (0., 0., 0., 0.). - stds (Sequence[float]): Denormalizing standard deviation for delta - coordinates. Default (1., 1., 1., 1.). - max_shape (Sequence[int] or torch.Tensor or Sequence[ - Sequence[int]],optional): Maximum bounds for boxes, specifies - (H, W, C) or (H, W). If rois shape is (B, N, 4), then - the max_shape should be a Sequence[Sequence[int]] - and the length of max_shape should also be B. Default None. - wh_ratio_clip (float): Maximum aspect ratio for boxes. - Default 16 / 1000. - clip_border (bool, optional): Whether clip the objects outside the - border of the image. Default True. - add_ctr_clamp (bool): Whether to add center clamp, when added, the - predicted box is clamped is its center is too far away from - the original anchor's center. Only used by YOLOF. Default False. - ctr_clamp (int): the maximum pixel shift to clamp. Only used by YOLOF. - Default 32. - - Returns: - Tensor: Boxes with shape (B, N, num_classes * 4) or (B, N, 4) or - (N, num_classes * 4) or (N, 4), where 4 represent - tl_x, tl_y, br_x, br_y. - - References: - .. [1] https://arxiv.org/abs/1311.2524 - - Example: - >>> rois = torch.Tensor([[ 0., 0., 1., 1.], - >>> [ 0., 0., 1., 1.], - >>> [ 0., 0., 1., 1.], - >>> [ 5., 5., 5., 5.]]) - >>> deltas = torch.Tensor([[ 0., 0., 0., 0.], - >>> [ 1., 1., 1., 1.], - >>> [ 0., 0., 2., -1.], - >>> [ 0.7, -1.9, -0.5, 0.3]]) - >>> delta2bbox(rois, deltas, max_shape=(32, 32, 3)) - tensor([[0.0000, 0.0000, 1.0000, 1.0000], - [0.1409, 0.1409, 2.8591, 2.8591], - [0.0000, 0.3161, 4.1945, 0.6839], - [5.0000, 5.0000, 5.0000, 5.0000]]) - """ - means = deltas.new_tensor(means).view(1, - -1).repeat(1, - deltas.size(-1) // 4) - stds = deltas.new_tensor(stds).view(1, -1).repeat(1, deltas.size(-1) // 4) - denorm_deltas = deltas * stds + means - dx = denorm_deltas[..., 0::4] - dy = denorm_deltas[..., 1::4] - dw = denorm_deltas[..., 2::4] - dh = denorm_deltas[..., 3::4] - - x1, y1 = rois[..., 0], rois[..., 1] - x2, y2 = rois[..., 2], rois[..., 3] - # Compute center of each roi - px = ((x1 + x2) * 0.5).unsqueeze(-1).expand_as(dx) - py = ((y1 + y2) * 0.5).unsqueeze(-1).expand_as(dy) - # Compute width/height of each roi - pw = (x2 - x1).unsqueeze(-1).expand_as(dw) - ph = (y2 - y1).unsqueeze(-1).expand_as(dh) - - dx_width = pw * dx - dy_height = ph * dy - - max_ratio = np.abs(np.log(wh_ratio_clip)) - if add_ctr_clamp: - dx_width = torch.clamp(dx_width, max=ctr_clamp, min=-ctr_clamp) - dy_height = torch.clamp(dy_height, max=ctr_clamp, min=-ctr_clamp) - dw = torch.clamp(dw, max=max_ratio) - dh = torch.clamp(dh, max=max_ratio) - else: - dw = dw.clamp(min=-max_ratio, max=max_ratio) - dh = dh.clamp(min=-max_ratio, max=max_ratio) - # Use exp(network energy) to enlarge/shrink each roi - gw = pw * dw.exp() - gh = ph * dh.exp() - # Use network energy to shift the center of each roi - gx = px + dx_width - gy = py + dy_height - # Convert center-xy/width/height to top-left, bottom-right - x1 = gx - gw * 0.5 - y1 = gy - gh * 0.5 - x2 = gx + gw * 0.5 - y2 = gy + gh * 0.5 - - bboxes = torch.stack([x1, y1, x2, y2], dim=-1).view(deltas.size()) - - if clip_border and max_shape is not None: - # clip bboxes with dynamic `min` and `max` for onnx - if torch.onnx.is_in_onnx_export(): - from mmdet.core.export import dynamic_clip_for_onnx - x1, y1, x2, y2 = dynamic_clip_for_onnx(x1, y1, x2, y2, max_shape) - bboxes = torch.stack([x1, y1, x2, y2], dim=-1).view(deltas.size()) - return bboxes - if not isinstance(max_shape, torch.Tensor): - max_shape = x1.new_tensor(max_shape) - max_shape = max_shape[..., :2].type_as(x1) - if max_shape.ndim == 2: - assert bboxes.ndim == 3 - assert max_shape.size(0) == bboxes.size(0) - - min_xy = x1.new_tensor(0) - max_xy = torch.cat( - [max_shape] * (deltas.size(-1) // 2), - dim=-1).flip(-1).unsqueeze(-2) - bboxes = torch.where(bboxes < min_xy, min_xy, bboxes) - bboxes = torch.where(bboxes > max_xy, max_xy, bboxes) - - return bboxes diff --git a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/models/seg_heads/panoptic_fusion_heads/heuristic_fusion_head.py b/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/models/seg_heads/panoptic_fusion_heads/heuristic_fusion_head.py deleted file mode 100644 index 06c1de2b9010fef13bd2322bbd3352d82a1f3e2f..0000000000000000000000000000000000000000 --- a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/models/seg_heads/panoptic_fusion_heads/heuristic_fusion_head.py +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch - -from mmdet.core.evaluation.panoptic_utils import INSTANCE_OFFSET -from mmdet.models.builder import HEADS -from .base_panoptic_fusion_head import BasePanopticFusionHead - - -@HEADS.register_module() -class HeuristicFusionHead(BasePanopticFusionHead): - """Fusion Head with Heuristic method.""" - - def __init__(self, - num_things_classes=80, - num_stuff_classes=53, - test_cfg=None, - init_cfg=None, - **kwargs): - super(HeuristicFusionHead, - self).__init__(num_things_classes, num_stuff_classes, test_cfg, - None, init_cfg, **kwargs) - - def forward_train(self, gt_masks=None, gt_semantic_seg=None, **kwargs): - """HeuristicFusionHead has no training loss.""" - return dict() - - def _lay_masks(self, bboxes, labels, masks, overlap_thr=0.5): - """Lay instance masks to a result map. - - Args: - bboxes: The bboxes results, (K, 4). - labels: The labels of bboxes, (K, ). - masks: The instance masks, (K, H, W). - overlap_thr: Threshold to determine whether two masks overlap. - default: 0.5. - - Returns: - Tensor: The result map, (H, W). - """ - num_insts = bboxes.shape[0] - id_map = torch.zeros( - masks.shape[-2:], device=bboxes.device, dtype=torch.long) - if num_insts == 0: - return id_map, labels - - scores, bboxes = bboxes[:, -1], bboxes[:, :4] - - # Sort by score to use heuristic fusion - order = torch.argsort(-scores) - bboxes = bboxes[order] - labels = labels[order] - segm_masks = masks[order] - - instance_id = 1 - left_labels = [] - for idx in range(bboxes.shape[0]): - _cls = labels[idx] - _mask = segm_masks[idx] - instance_id_map = torch.ones_like( - _mask, dtype=torch.long) * instance_id - area = _mask.sum() - if area == 0: - continue - - pasted = id_map > 0 - intersect = (_mask * pasted).sum() - if (intersect / (area + 1e-5)) > overlap_thr: - continue - - _part = _mask * (~pasted) - id_map = torch.where(_part, instance_id_map, id_map) - left_labels.append(_cls) - instance_id += 1 - - if len(left_labels) > 0: - instance_labels = torch.stack(left_labels) - else: - instance_labels = bboxes.new_zeros((0, ), dtype=torch.long) - assert instance_id == (len(instance_labels) + 1) - return id_map, instance_labels - - def simple_test(self, det_bboxes, det_labels, mask_preds, seg_preds, - **kwargs): - """Fuse the results of instance and semantic segmentations. - - Args: - det_bboxes: The bboxes results, (K, 4). - det_labels: The labels of bboxes, (K,). - mask_preds: The masks results, (K, H, W). - seg_preds: The semantic segmentation results, - (K, num_stuff + 1, H, W). - - Returns: - Tensor : The panoptic segmentation result, (H, W). - """ - mask_preds = mask_preds >= self.test_cfg.mask_thr_binary - id_map, labels = self._lay_masks(det_bboxes, det_labels, mask_preds, - self.test_cfg.mask_overlap) - - seg_results = seg_preds.argmax(dim=0) - seg_results = seg_results + self.num_things_classes - - pan_results = seg_results - instance_id = 1 - for idx in range(det_labels.shape[0]): - _mask = id_map == (idx + 1) - if _mask.sum() == 0: - continue - _cls = labels[idx] - # simply trust detection - segment_id = _cls + instance_id * INSTANCE_OFFSET - pan_results[_mask] = segment_id - instance_id += 1 - - ids, counts = torch.unique( - pan_results % INSTANCE_OFFSET, return_counts=True) - stuff_ids = ids[ids >= self.num_things_classes] - stuff_counts = counts[ids >= self.num_things_classes] - ignore_stuff_ids = stuff_ids[ - stuff_counts < self.test_cfg.stuff_area_limit] - - assert pan_results.ndim == 2 - pan_results[(pan_results.unsqueeze(2) == ignore_stuff_ids.reshape( - 1, 1, -1)).any(dim=2)] = self.num_classes - - return pan_results diff --git a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/projects/instance_segment_anything/models/focalnet_dino/models/dino/util/misc.py b/spaces/rockeycoss/Prompt-Segment-Anything-Demo/projects/instance_segment_anything/models/focalnet_dino/models/dino/util/misc.py deleted file mode 100644 index 7d2f4d7fdfb303bddef004a6536983914024da89..0000000000000000000000000000000000000000 --- a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/projects/instance_segment_anything/models/focalnet_dino/models/dino/util/misc.py +++ /dev/null @@ -1,587 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -""" -Misc functions, including distributed helpers. - -Mostly copy-paste from torchvision references. -""" -import os -import random -import subprocess -import time -from collections import OrderedDict, defaultdict, deque -import datetime -import pickle -from typing import Optional, List - -import json, time -import numpy as np -import torch -import torch.distributed as dist -from torch import Tensor - -import colorsys - -# needed due to empty tensor bug in pytorch and torchvision 0.5 -import torchvision -__torchvision_need_compat_flag = float(torchvision.__version__.split('.')[1]) < 7 -if __torchvision_need_compat_flag: - from torchvision.ops import _new_empty_tensor - from torchvision.ops.misc import _output_size - - -class SmoothedValue(object): - """Track a series of values and provide access to smoothed values over a - window or the global series average. - """ - - def __init__(self, window_size=20, fmt=None): - if fmt is None: - fmt = "{median:.4f} ({global_avg:.4f})" - self.deque = deque(maxlen=window_size) - self.total = 0.0 - self.count = 0 - self.fmt = fmt - - def update(self, value, n=1): - self.deque.append(value) - self.count += n - self.total += value * n - - def synchronize_between_processes(self): - """ - Warning: does not synchronize the deque! - """ - if not is_dist_avail_and_initialized(): - return - t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') - dist.barrier() - dist.all_reduce(t) - t = t.tolist() - self.count = int(t[0]) - self.total = t[1] - - @property - def median(self): - d = torch.tensor(list(self.deque)) - if d.shape[0] == 0: - return 0 - return d.median().item() - - @property - def avg(self): - d = torch.tensor(list(self.deque), dtype=torch.float32) - return d.mean().item() - - @property - def global_avg(self): - return self.total / self.count - - @property - def max(self): - return max(self.deque) - - @property - def value(self): - return self.deque[-1] - - def __str__(self): - return self.fmt.format( - median=self.median, - avg=self.avg, - global_avg=self.global_avg, - max=self.max, - value=self.value) - - -def all_gather(data): - """ - Run all_gather on arbitrary picklable data (not necessarily tensors) - Args: - data: any picklable object - Returns: - list[data]: list of data gathered from each rank - """ - world_size = get_world_size() - if world_size == 1: - return [data] - - # serialized to a Tensor - buffer = pickle.dumps(data) - storage = torch.ByteStorage.from_buffer(buffer) - tensor = torch.ByteTensor(storage).to("cuda") - - # obtain Tensor size of each rank - local_size = torch.tensor([tensor.numel()], device="cuda") - size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] - dist.all_gather(size_list, local_size) - size_list = [int(size.item()) for size in size_list] - max_size = max(size_list) - - # receiving Tensor from all ranks - # we pad the tensor because torch all_gather does not support - # gathering tensors of different shapes - tensor_list = [] - for _ in size_list: - tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) - if local_size != max_size: - padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") - tensor = torch.cat((tensor, padding), dim=0) - dist.all_gather(tensor_list, tensor) - - data_list = [] - for size, tensor in zip(size_list, tensor_list): - buffer = tensor.cpu().numpy().tobytes()[:size] - data_list.append(pickle.loads(buffer)) - - return data_list - - -def reduce_dict(input_dict, average=True): - """ - Args: - input_dict (dict): all the values will be reduced - average (bool): whether to do average or sum - Reduce the values in the dictionary from all processes so that all processes - have the averaged results. Returns a dict with the same fields as - input_dict, after reduction. - """ - world_size = get_world_size() - if world_size < 2: - return input_dict - with torch.no_grad(): - names = [] - values = [] - # sort the keys so that they are consistent across processes - for k in sorted(input_dict.keys()): - names.append(k) - values.append(input_dict[k]) - values = torch.stack(values, dim=0) - dist.all_reduce(values) - if average: - values /= world_size - reduced_dict = {k: v for k, v in zip(names, values)} - return reduced_dict - - -class MetricLogger(object): - def __init__(self, delimiter="\t"): - self.meters = defaultdict(SmoothedValue) - self.delimiter = delimiter - - def update(self, **kwargs): - for k, v in kwargs.items(): - if isinstance(v, torch.Tensor): - v = v.item() - assert isinstance(v, (float, int)) - self.meters[k].update(v) - - def __getattr__(self, attr): - if attr in self.meters: - return self.meters[attr] - if attr in self.__dict__: - return self.__dict__[attr] - raise AttributeError("'{}' object has no attribute '{}'".format( - type(self).__name__, attr)) - - def __str__(self): - loss_str = [] - for name, meter in self.meters.items(): - # print(name, str(meter)) - # import ipdb;ipdb.set_trace() - if meter.count > 0: - loss_str.append( - "{}: {}".format(name, str(meter)) - ) - return self.delimiter.join(loss_str) - - def synchronize_between_processes(self): - for meter in self.meters.values(): - meter.synchronize_between_processes() - - def add_meter(self, name, meter): - self.meters[name] = meter - - def log_every(self, iterable, print_freq, header=None, logger=None): - if logger is None: - print_func = print - else: - print_func = logger.info - - i = 0 - if not header: - header = '' - start_time = time.time() - end = time.time() - iter_time = SmoothedValue(fmt='{avg:.4f}') - data_time = SmoothedValue(fmt='{avg:.4f}') - space_fmt = ':' + str(len(str(len(iterable)))) + 'd' - if torch.cuda.is_available(): - log_msg = self.delimiter.join([ - header, - '[{0' + space_fmt + '}/{1}]', - 'eta: {eta}', - '{meters}', - 'time: {time}', - 'data: {data}', - 'max mem: {memory:.0f}' - ]) - else: - log_msg = self.delimiter.join([ - header, - '[{0' + space_fmt + '}/{1}]', - 'eta: {eta}', - '{meters}', - 'time: {time}', - 'data: {data}' - ]) - MB = 1024.0 * 1024.0 - for obj in iterable: - data_time.update(time.time() - end) - yield obj - # import ipdb; ipdb.set_trace() - iter_time.update(time.time() - end) - if i % print_freq == 0 or i == len(iterable) - 1: - eta_seconds = iter_time.global_avg * (len(iterable) - i) - eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) - if torch.cuda.is_available(): - print_func(log_msg.format( - i, len(iterable), eta=eta_string, - meters=str(self), - time=str(iter_time), data=str(data_time), - memory=torch.cuda.max_memory_allocated() / MB)) - else: - print_func(log_msg.format( - i, len(iterable), eta=eta_string, - meters=str(self), - time=str(iter_time), data=str(data_time))) - i += 1 - end = time.time() - total_time = time.time() - start_time - total_time_str = str(datetime.timedelta(seconds=int(total_time))) - print_func('{} Total time: {} ({:.4f} s / it)'.format( - header, total_time_str, total_time / len(iterable))) - - -def get_sha(): - cwd = os.path.dirname(os.path.abspath(__file__)) - - def _run(command): - return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() - sha = 'N/A' - diff = "clean" - branch = 'N/A' - try: - sha = _run(['git', 'rev-parse', 'HEAD']) - subprocess.check_output(['git', 'diff'], cwd=cwd) - diff = _run(['git', 'diff-index', 'HEAD']) - diff = "has uncommited changes" if diff else "clean" - branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) - except Exception: - pass - message = f"sha: {sha}, status: {diff}, branch: {branch}" - return message - - -def collate_fn(batch): - # import ipdb; ipdb.set_trace() - batch = list(zip(*batch)) - batch[0] = nested_tensor_from_tensor_list(batch[0]) - return tuple(batch) - - -def _max_by_axis(the_list): - # type: (List[List[int]]) -> List[int] - maxes = the_list[0] - for sublist in the_list[1:]: - for index, item in enumerate(sublist): - maxes[index] = max(maxes[index], item) - return maxes - - -class NestedTensor(object): - def __init__(self, tensors, mask: Optional[Tensor]): - self.tensors = tensors - self.mask = mask - if mask == 'auto': - self.mask = torch.zeros_like(tensors).to(tensors.device) - if self.mask.dim() == 3: - self.mask = self.mask.sum(0).to(bool) - elif self.mask.dim() == 4: - self.mask = self.mask.sum(1).to(bool) - else: - raise ValueError("tensors dim must be 3 or 4 but {}({})".format(self.tensors.dim(), self.tensors.shape)) - - def imgsize(self): - res = [] - for i in range(self.tensors.shape[0]): - mask = self.mask[i] - maxH = (~mask).sum(0).max() - maxW = (~mask).sum(1).max() - res.append(torch.Tensor([maxH, maxW])) - return res - - def to(self, device): - # type: (Device) -> NestedTensor # noqa - cast_tensor = self.tensors.to(device) - mask = self.mask - if mask is not None: - assert mask is not None - cast_mask = mask.to(device) - else: - cast_mask = None - return NestedTensor(cast_tensor, cast_mask) - - def to_img_list_single(self, tensor, mask): - assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim()) - maxH = (~mask).sum(0).max() - maxW = (~mask).sum(1).max() - img = tensor[:, :maxH, :maxW] - return img - - def to_img_list(self): - """remove the padding and convert to img list - - Returns: - [type]: [description] - """ - if self.tensors.dim() == 3: - return self.to_img_list_single(self.tensors, self.mask) - else: - res = [] - for i in range(self.tensors.shape[0]): - tensor_i = self.tensors[i] - mask_i = self.mask[i] - res.append(self.to_img_list_single(tensor_i, mask_i)) - return res - - @property - def device(self): - return self.tensors.device - - def decompose(self): - return self.tensors, self.mask - - def __repr__(self): - return str(self.tensors) - - @property - def shape(self): - return { - 'tensors.shape': self.tensors.shape, - 'mask.shape': self.mask.shape - } - - -def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): - # TODO make this more general - if tensor_list[0].ndim == 3: - if torchvision._is_tracing(): - # nested_tensor_from_tensor_list() does not export well to ONNX - # call _onnx_nested_tensor_from_tensor_list() instead - return _onnx_nested_tensor_from_tensor_list(tensor_list) - - # TODO make it support different-sized images - max_size = _max_by_axis([list(img.shape) for img in tensor_list]) - # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) - batch_shape = [len(tensor_list)] + max_size - b, c, h, w = batch_shape - dtype = tensor_list[0].dtype - device = tensor_list[0].device - tensor = torch.zeros(batch_shape, dtype=dtype, device=device) - mask = torch.ones((b, h, w), dtype=torch.bool, device=device) - for img, pad_img, m in zip(tensor_list, tensor, mask): - pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) - m[: img.shape[1], :img.shape[2]] = False - else: - raise ValueError('not supported') - return NestedTensor(tensor, mask) - - -# _onnx_nested_tensor_from_tensor_list() is an implementation of -# nested_tensor_from_tensor_list() that is supported by ONNX tracing. -@torch.jit.unused -def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor: - max_size = [] - for i in range(tensor_list[0].dim()): - max_size_i = torch.max(torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)).to(torch.int64) - max_size.append(max_size_i) - max_size = tuple(max_size) - - # work around for - # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) - # m[: img.shape[1], :img.shape[2]] = False - # which is not yet supported in onnx - padded_imgs = [] - padded_masks = [] - for img in tensor_list: - padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] - padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) - padded_imgs.append(padded_img) - - m = torch.zeros_like(img[0], dtype=torch.int, device=img.device) - padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1) - padded_masks.append(padded_mask.to(torch.bool)) - - tensor = torch.stack(padded_imgs) - mask = torch.stack(padded_masks) - - return NestedTensor(tensor, mask=mask) - - -def setup_for_distributed(is_master): - """ - This function disables printing when not in master process - """ - import builtins as __builtin__ - builtin_print = __builtin__.print - - def print(*args, **kwargs): - force = kwargs.pop('force', False) - if is_master or force: - builtin_print(*args, **kwargs) - - __builtin__.print = print - - -def is_dist_avail_and_initialized(): - if not dist.is_available(): - return False - if not dist.is_initialized(): - return False - return True - - -def get_world_size(): - if not is_dist_avail_and_initialized(): - return 1 - return dist.get_world_size() - - -def get_rank(): - if not is_dist_avail_and_initialized(): - return 0 - return dist.get_rank() - - -def is_main_process(): - return get_rank() == 0 - - -def save_on_master(*args, **kwargs): - if is_main_process(): - torch.save(*args, **kwargs) - - -def init_distributed_mode(args): - if 'WORLD_SIZE' in os.environ and os.environ['WORLD_SIZE'] != '': # 'RANK' in os.environ and - # args.rank = int(os.environ["RANK"]) - # args.world_size = int(os.environ['WORLD_SIZE']) - # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) - - # launch by torch.distributed.launch - # Single node - # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ... - # Multi nodes - # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... - # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... - - local_world_size = int(os.environ['WORLD_SIZE']) - args.world_size = args.world_size * local_world_size - args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) - args.rank = args.rank * local_world_size + args.local_rank - print('world size: {}, rank: {}, local rank: {}'.format(args.world_size, args.rank, args.local_rank)) - print(json.dumps(dict(os.environ), indent=2)) - elif 'SLURM_PROCID' in os.environ: - args.rank = int(os.environ['SLURM_PROCID']) - args.gpu = args.local_rank = int(os.environ['SLURM_LOCALID']) - args.world_size = int(os.environ['SLURM_NPROCS']) - - print('world size: {}, world rank: {}, local rank: {}, device_count: {}'.format(args.world_size, args.rank, args.local_rank, torch.cuda.device_count())) - else: - print('Not using distributed mode') - args.distributed = False - args.world_size = 1 - args.rank = 0 - args.local_rank = 0 - return - - print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank)) - args.distributed = True - torch.cuda.set_device(args.local_rank) - args.dist_backend = 'nccl' - print('| distributed init (rank {}): {}'.format(args.rank, args.dist_url), flush=True) - torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, - world_size=args.world_size, rank=args.rank) - print("Before torch.distributed.barrier()") - torch.distributed.barrier() - print("End torch.distributed.barrier()") - setup_for_distributed(args.rank == 0) - - -@torch.no_grad() -def accuracy(output, target, topk=(1,)): - """Computes the precision@k for the specified values of k""" - if target.numel() == 0: - return [torch.zeros([], device=output.device)] - maxk = max(topk) - batch_size = target.size(0) - - _, pred = output.topk(maxk, 1, True, True) - pred = pred.t() - correct = pred.eq(target.view(1, -1).expand_as(pred)) - - res = [] - for k in topk: - correct_k = correct[:k].view(-1).float().sum(0) - res.append(correct_k.mul_(100.0 / batch_size)) - return res - - -def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): - # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor - """ - Equivalent to nn.functional.interpolate, but with support for empty batch sizes. - This will eventually be supported natively by PyTorch, and this - class can go away. - """ - if __torchvision_need_compat_flag < 0.7: - if input.numel() > 0: - return torch.nn.functional.interpolate( - input, size, scale_factor, mode, align_corners - ) - - output_shape = _output_size(2, input, size, scale_factor) - output_shape = list(input.shape[:-2]) + list(output_shape) - return _new_empty_tensor(input, output_shape) - else: - return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) - - - -class color_sys(): - def __init__(self, num_colors) -> None: - self.num_colors = num_colors - colors=[] - for i in np.arange(0., 360., 360. / num_colors): - hue = i/360. - lightness = (50 + np.random.rand() * 10)/100. - saturation = (90 + np.random.rand() * 10)/100. - colors.append(tuple([int(j*255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)])) - self.colors = colors - - def __call__(self, idx): - return self.colors[idx] - -def inverse_sigmoid(x, eps=1e-3): - x = x.clamp(min=0, max=1) - x1 = x.clamp(min=eps) - x2 = (1 - x).clamp(min=eps) - return torch.log(x1/x2) - -def clean_state_dict(state_dict): - new_state_dict = OrderedDict() - for k, v in state_dict.items(): - if k[:7] == 'module.': - k = k[7:] # remove `module.` - new_state_dict[k] = v - return new_state_dict \ No newline at end of file diff --git a/spaces/rorallitri/biomedical-language-models/logs/3D Max Mac Download Free Everything You Need to Know About the Popular 3D Software.md b/spaces/rorallitri/biomedical-language-models/logs/3D Max Mac Download Free Everything You Need to Know About the Popular 3D Software.md deleted file mode 100644 index 37220b44dedc7fb12a23551e23aac5b09c687d6a..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/3D Max Mac Download Free Everything You Need to Know About the Popular 3D Software.md +++ /dev/null @@ -1,28 +0,0 @@ - -

    Autodesk provides download and install instructions for individuals and administrators. Your available downloads appear in Autodesk Account or education site. Find your product, select a version, platform, language, and download method. For more information, visit the Autodesk Knowledge Network.

    -

    3d Max Mac Download Free


    DOWNLOADhttps://tinurll.com/2uzmzy



    -

    Trial versions of Autodesk software offer the chance to explore the full capabilities of the latest versions for a limited term (typically 30 days). To cancel a free trial, turn off automatic renewal before the trial period ends. If you were not required to enter a payment method at the start of the trial, it will expire automatically.

    -

    If your installation or product download fails, try using the Browser Download method instead (not available in macOS). We recommend disabling pop-up blockers and trying a different browser, such as Chrome or Explorer. For more solutions, check out our guide to troubleshooting Autodesk product download issues.

    -

    Students and educators can get free one-year educational access to Autodesk products and services, renewable as long as you remain eligible. If you are a student or educator, you can access free 3ds Max software with an Autodesk Education plan.

    -

    Autodesk provides download and install instructions for individuals and administrators. Your available downloads appear in Autodesk Account or education site. Find your product, select a version, platform, language, and download method. For more information, visit the Autodesk Knowledge Network.\n"}]},"@type":"Question","name":"How long is the 3ds Max free trial?","acceptedAnswer":["@type":"Answer","text":"Trial versions of Autodesk software offer the chance to explore the full capabilities of the latest versions for a limited term (typically 30 days). To cancel a free trial, turn off automatic renewal before the trial period ends. If you were not required to enter a payment method at the start of the trial, it will expire automatically.\r\n"],"@type":"Question","name":"How do I extend the 3ds Max free trial?","acceptedAnswer":["@type":"Answer","text":"If your trial expires, you cannot extend the trial period. For short-term needs, you can purchase a monthly subscription and turn off automatic renewal (to limit the length of the paid subscription to one month only) or purchase Flex tokens for a flexible pay-as-you-go plan.\r\n"],"@type":"Question","name":"How do I troubleshoot 3ds Max download issues?","acceptedAnswer":["@type":"Answer","text":"If your installation or product download fails, try using the Browser Download method instead (not available in macOS). We recommend disabling pop-up blockers and trying a different browser, such as Chrome or Explorer. For more solutions, check out our guide to troubleshooting Autodesk product download issues.\r\n"],"@type":"Question","name":"Where do I download free 3ds Max software for students?","acceptedAnswer":["@type":"Answer","text":"Students and educators can get free one-year educational access to Autodesk products and services, renewable as long as you remain eligible. If you are a student or educator, you can access free 3ds Max software with an Autodesk Education plan.\r\n"],"@type":"Question","name":"How do I convert my 3ds Max free trial to a paid subscription?","acceptedAnswer":["@type":"Answer","text":"Launch your trial software and click Subscribe Now on the trial screen or visit the 3ds Max product center. When buying your subscription, enter the same email address and password combination you used to sign in to your trial. Learn more about converting a trial to a paid subscription.\r\n"]],"@type":"FAQPage","@context":" "} Autodesk Company overview Careers Investor relations Newsroom Diversity and belonging

  4. Autodesk Foundation Sustainability Contact us Students and educators Affiliate program Autodesk Research How to buy

    -

    For stakeholders who only need file-viewing access, we offer free viewers without a subscription. If you're transitioning to named user, be sure to take advantage of the trade-in offers available to you.

    -

    -

    In this tutorial, we will explain step by step how to free download, install and license 3ds Max (3D Studio Max), 3ds Max for Mac on your computer. Register account and login to AUTODESK site. Check computer and internet performance. Currently available 3ds Max versions for free downloading and install are: 2021 and 2020.

    -

    For more about how to free download, install and license other CAD software tools, read in our tutorials: SOLIDWORKS 2021, 2020, 2019, 2018, 2017, 2016, 2015, FreeCAD, Free Download AutoCAD LT for Win/Mac and Altium Designer 21, 20, 19, 18, 17, 16, 15, 14, 13 and 10.

    -

    Synfig Studio is a free and open-source 2D animation software, designed as powerful industrial-strength solution for creating film-quality animation using a vector and bitmap artwork. It eliminates the need to create animation frame-by frame, allowing you to produce 2D animation of a higher quality with fewer people and resources.

    -

    The same as ALC BETACLEANER, but with some differences.

    The most dangerous thing is that this virus can download updates for itself and can be modified!

    This virus take next issues:

    -

    MeshLab 2021.07 is out! In this version we introduce support to several file formats (*.gltf, *.glb, *.nxs, *.nxz, *.e57) and a brand new plugin for exact mesh booleans. You can download in the download section, or in the github release page.

    -

    MeshLab sources are distributed under the GPL 3.0 Licensing Scheme.
    The 'MeshLab' name is a EUIPO trademark owned by CNR.
    MeshLab Logos ( ) are distributed under
    Creative Commons Attribution-Sharealike 4.0 International License and they can be freely used inside any wikimedia project.

    -

    You must also have an internal optical drive for installing Windows. Windows cannot be installed from an external optical drive. Windows must be installed on an internal drive if you use Boot Camp. A license must be purchased for all commercial software and operating system products. Open Source software is free.

    -

    The SPECviewperf 2020 V3.0 benchmark was released on December 9, 2021. It is supported under Microsoft Windows 10 64-bit platforms. Included in this new release are updates to the SOLIDWORKS-07 viewset, and viewsets are now individually downloaded and may be independently installed and removed using the new "Manage Viewsets" utility. Results from SPECviewperf 2020 V3.0 are not comparable to those from previous versions.

    -

    The SPECviewperf 2020 V2.0 benchmark was released on June 23, 2021. It is supported under Microsoft Windows 10 64-bit platforms. Included in this new release are updates to the SOLIDWORKS-06 viewset, and viewsets are now individually downloaded and may be independently installed and removed using the new "Manage Viewsets" utility. Results from SPECviewperf 2020 V2.0 are not comparable to those from previous versions.

    -

    On February 25, 2020, the SPECwpc subcommittee released version 3.0.4 of the SPECworkstation benchmark, enabling certain computational workloads to scale beyond 64 logical processors. The update is available in two forms: as a minor-version patch to the benchmark for those already using SPECworkstation 3.0.3, and as a full benchmark installation. If your already installed version of SPECworkstation is lower than 3.0.3, the full benchmark installation package should be used instead of the patch. Whether you download the full V3.0.4 benchmark or just the patch, you will retain comparability between 3.0.4 and all previous 3.0 versions.

    -

    To install the patch, extract the contents of the downloaded zip file into an existing SPECworkstation 3.0.3 installation folder, overwriting files when prompted. Users can verify their installation of SPECworkstation has been patched successfully by confirming that the version number shown in the application title bar and the results files matches "3.0.4".

    -

    fSpy is open source software and totally free to download and use. But just in case you think it makes sense to pay for fSpy, here's a donate button! Pay as much or as little as you want.

    -

    For those of you who are searching for the download links of the free Mental Ray software, which we did publish in the forum as well, here you are. We include a copy of the text of the original announcement followed by all the links to the pieces of software.

    -

    Please note, the plugins are free to use for interactive rendering and rendering of still frames from within Maya or 3ds Max. The rendering of animations with Maya Batch, Backburner or Mental Ray Standalone will ask for a license though.

    -

    Hi all, we have fixed the download links for the older 2017 and 2016 versions of the Mental Ray software for Maya. Please keep in mind, those products have been built many years back for systems and hardware available at the time. Have fun!

    -

    The following list of software includes popular campus applications utilized by students and other academic constituents. Although it is recommended students download and install the following applications on their own computing devices, the new Virtual Software Lab service is also available as an alternative option in accessing student software if necessary. The following software is available for students to download and install on their personal computers. The campus cannot provide support for the installation or operation of the following software on personal equipment. Please contact your own computer support contacts or technical support businesses for personal computer assistance. You may contact the IT Service Desk at 869-6776 (x6776) for additional information about the following software.

    -

    Download VideoPad Video Editor for Windows

    • Supports all popular video formats seamlessly
      Edit video from a DV camcorder, VHS, GoPro, webcam, or all common video file formats including avi, wmv, divx, mp4, apng, mpeg and many more. Breathtaking transitions and visual effects
      Over 50 visual and transition effects to add a professional touch to your movies.
    Get it Free. A free video editor version is available for non-commercial use only. If you will be using it at home you can download the free version here. No signup required. Drag and drop video clips
    for easy video editing

    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/rorallitri/biomedical-language-models/logs/Android TTPod Skin TSK Where to Find and Download Skins.md b/spaces/rorallitri/biomedical-language-models/logs/Android TTPod Skin TSK Where to Find and Download Skins.md deleted file mode 100644 index ffe142cb515b11c25d2215da61346c2fda5b67cb..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Android TTPod Skin TSK Where to Find and Download Skins.md +++ /dev/null @@ -1,14 +0,0 @@ -
    -

    TSK files are used for customizing the TTPod app. The file is used for storing default skins or skins created by a TTPod users. A skin includes the appearance of the background, menus, text, buttons, lines, and margins.

    -

    Our free tsk converter online tools does not required any registrations and installations on your system, 100% free and online ttpod skin (.tsk) converter tool. Open from any device with a modern browser like Chrome, Opera and Firefox.

    -

    android ttpod skin tsk


    Download File 🆓 https://tinurll.com/2uzlzJ



    -

    Our free tsk viewer online tools does not required any registrations and installations on your system, 100% free and online ttpod skin (.tsk) viewer tool. Open from any device with a modern browser like Chrome, Opera and Firefox.

    -

    Great site! Using ttpod for quite some time not to mention I am still using the old version. because I just love it and its user interface. which looks nothing like too much as the modern or up-to-date MP3 player that we see today I do have a lot of the other skin that came out or themes just wondering if there were more on their site. Other than that you are indeed godsend thanks.

    -

    Un file TSK contiene uno skin utilizzato da TTPod, un lettore musicale per dispositivi Android. Memorizza una skin per il lettore che configura l'aspetto del lettore TTPod. I file TSK sono memorizzati nella directory / SDCard / TTPod / Skin.

    -

    I file TSK vengono utilizzati per personalizzare l'app TTPod. Il file viene utilizzato per la memorizzazione di skin o skin predefiniti creati da utenti TTPod. Una skin include l'aspetto di sfondo, menu, testo, pulsanti, linee e margini.

    -

    Un fichier TSK contient un skin utilisé par TTPod, un lecteur de musique pour les appareils Android. Il stocke une peau pour le lecteur qui configure l'apparence du lecteur TTPod. Les fichiers TSK sont stockés dans le répertoire / SDCard / TTPod / Skin.

    -

    ttpod versi 3 ke atas emang belom support ke Inggris, bro.. Sebenernya kan versi 3 ke atas itu untuk Symbian, tapi entah kenapa di android juga diberi kode itu..
    Aku aja sampe sekarang masih pake versi 2.9 (patch ke berapa entahlah)..

    -

    -

    Un archivo TSK contiene un skin utilizado por TTPod, un reproductor de música para dispositivos Android. Almacena un skin para el reproductor que configura la apariencia del reproductor TTPod. Los archivos TSK se almacenan en el directorio /SDCard/TTPod/Skin. Más información Los archivos TSK se utilizan para personalizar la aplicación TTPod. El archivo se utiliza para almacenar skins por defecto o skins creados por un usuario de TTPod. Un skin incluye la apariencia del fondo, los menús, el texto, los botones, las líneas y los márgenes.

    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/rorallitri/biomedical-language-models/logs/Crysis 2 Serial Keygen Download __LINK__.md b/spaces/rorallitri/biomedical-language-models/logs/Crysis 2 Serial Keygen Download __LINK__.md deleted file mode 100644 index 2f6346cad71f0114ecfca883a37172de73a9ad8f..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/Crysis 2 Serial Keygen Download __LINK__.md +++ /dev/null @@ -1,33 +0,0 @@ -
    -

    Crysis 2 Serial Keygen Download - How to Play Crysis 2 Online for Free

    -

    If you are a fan of first-person shooter games, you might have heard of Crysis 2, a sci-fi game that lets you fight against aliens in a futuristic New York City. Crysis 2 is a stunning game that features amazing graphics, realistic physics and dynamic gameplay. However, if you want to play Crysis 2 online, you will need a valid serial key to activate the game.

    -

    Unfortunately, buying the original game can be quite expensive, and not everyone can afford it. That's why some people look for alternative ways to get Crysis 2 serial keygen download for free. A serial keygen is a program that generates random serial keys that can be used to activate the game. However, not all serial keygens are safe and reliable. Some of them may contain viruses, malware or spyware that can harm your computer or steal your personal information.

    -

    Crysis 2 Serial Keygen Download


    Download File >>> https://tinurll.com/2uznSH



    -

    So how can you find a trustworthy and working Crysis 2 serial keygen download? In this article, we will show you how to download and use a Crysis 2 serial keygen that is guaranteed to work and let you play Crysis 2 online without any problems. Follow these simple steps and enjoy the game!

    -

    Step 1: Download the Crysis 2 Serial Keygen

    -

    The first step is to download the Crysis 2 serial keygen from a reputable source. We recommend you to use this link: https://www.mediafire.com/file/924323... This is a verified and tested serial keygen that has been used by thousands of players around the world. It is safe, secure and easy to use.

    -

    Once you click on the link, you will be redirected to a Mediafire page where you can download the file. The file size is about 3 MB and it will take only a few seconds to download. After downloading the file, you will need to extract it using WinRAR or any other software that can open ZIP files.

    -

    Step 2: Run the Crysis 2 Serial Keygen

    -

    The next step is to run the Crysis 2 serial keygen on your computer. To do this, you will need to double-click on the file named "Crysis_2_Keygen.exe". A window will pop up with a simple interface. You will see a button that says "Generate". Click on it and wait for a few moments.

    -

    The serial keygen will generate a random serial key that can be used to activate Crysis 2 online. You will see the serial key displayed on the screen. It will look something like this: "5DKK-G7PQ-GKJM-FYUW-KNMP". Copy the serial key and save it somewhere safe.

    -

    Step 3: Activate Crysis 2 Online

    -

    The final step is to activate Crysis 2 online using the serial key that you have generated. To do this, you will need to have Crysis 2 installed on your computer. If you don't have it yet, you can download it from here: https://herevfiles134.weebly.com/crysis-2-activation-key-for-pc.html This is a cracked version of Crysis 2 that bypasses the activation process.

    -

    After installing Crysis 2, launch the game and go to the multiplayer mode. You will be asked to enter your serial key to access the online features. Paste the serial key that you have copied from the serial keygen and click on "Activate". You will see a message that says "Activation Successful". Congratulations! You have successfully activated Crysis 2 online and you can now play with other players around the world!

    -

    Conclusion

    -

    Crysis 2 is an amazing game that deserves to be played by everyone who loves first-person shooter games. However, buying the original game can be quite costly, and not everyone can afford it. That's why we have shown you how to get Crysis 2 serial keygen download for free and play Crysis 2 online without any hassle.

    -

    -

    We hope you have enjoyed this article and found it useful. If you have any questions or comments, feel free to leave them below. We would love to hear from you. And if you liked this article, please share it with your friends who might also be interested in playing Crysis 2 online for free. Thank you for reading and have fun!

    -

    Tips and Advice for Playing Crysis 2 Online

    -

    Now that you have activated Crysis 2 online, you might be wondering how to play the game and enjoy its features. Here are some tips and advice that will help you get the most out of Crysis 2 online:

    -
      -
    • Use the Nanosuit 2 abilities wisely. The Nanosuit 2 is a powerful suit that gives you four different modes: Stealth, Armor, Power and Nanovision. Each mode has its own advantages and disadvantages, and you can switch between them at any time. Stealth mode makes you invisible to enemies, but drains your energy quickly. Armor mode protects you from damage, but reduces your mobility. Power mode enhances your strength and speed, but makes you more visible. Nanovision mode allows you to see through smoke and darkness, but lowers your contrast.
    • -
    • Customize your loadout. Before joining a match, you can customize your loadout by choosing your primary weapon, secondary weapon, attachment, grenade type and dog tag. You can also unlock new weapons and attachments by earning experience points and ranking up. Try different combinations and find the one that suits your playstyle.
    • -
    • Play different game modes. Crysis 2 online offers several game modes that vary in objectives and rules. Some of the game modes are: Team Instant Action (team deathmatch), Instant Action (free-for-all deathmatch), Crash Site (capture and hold alien pods), Capture the Relay (capture the flag), Extraction (defend or attack a data carrier) and Assault (infiltrate or defend a base). Each game mode requires different strategies and skills, so experiment with them and have fun.
    • -
    • Communicate with your teammates. Crysis 2 online supports voice chat and text chat, so you can communicate with your teammates and coordinate your actions. You can also use the Nanosuit voice commands to give orders or request assistance. Communication is key to winning matches and having a good team spirit.
    • -
    • Enjoy the graphics and sound. Crysis 2 online features stunning graphics and sound that immerse you in the game world. The game uses the CryEngine 3 technology, which delivers realistic lighting, shadows, physics and animations. The game also has a dynamic soundtrack that adapts to the situation and mood of the game. The game also supports 3D vision for those who have compatible devices.
    • -
    -

    Conclusion

    -

    Crysis 2 online is an amazing experience that will keep you entertained for hours. With our Crysis 2 serial keygen download guide, you can play Crysis 2 online for free without any hassle. Just follow our simple steps and enjoy the game!

    -

    We hope you have enjoyed this article and found it useful. If you have any questions or comments, feel free to leave them below. We would love to hear from you. And if you liked this article, please share it with your friends who might also be interested in playing Crysis 2 online for free. Thank you for reading and have fun!

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/rstallman/Mayfair-Partner-Music/tests/quantization/test_vq.py b/spaces/rstallman/Mayfair-Partner-Music/tests/quantization/test_vq.py deleted file mode 100644 index c215099fedacae35c6798fdd9b8420a447aa16bb..0000000000000000000000000000000000000000 --- a/spaces/rstallman/Mayfair-Partner-Music/tests/quantization/test_vq.py +++ /dev/null @@ -1,18 +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 torch - -from audiocraft.quantization.vq import ResidualVectorQuantizer - - -class TestResidualVectorQuantizer: - - def test_rvq(self): - x = torch.randn(1, 16, 2048) - vq = ResidualVectorQuantizer(n_q=8, dimension=16, bins=8) - res = vq(x, 1.) - assert res.x.shape == torch.Size([1, 16, 2048]) diff --git a/spaces/saad-abdullah/knn-for-gdp-to-happiness-predictor/README.md b/spaces/saad-abdullah/knn-for-gdp-to-happiness-predictor/README.md deleted file mode 100644 index 4ef06c358fb32a98f9654a16ab50e94585211d82..0000000000000000000000000000000000000000 --- a/spaces/saad-abdullah/knn-for-gdp-to-happiness-predictor/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: knn-for-gdp-to-happiness-predictor -emoji: 😻 -colorFrom: purple -colorTo: indigo -sdk: gradio -sdk_version: 3.19.1 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/salahIguiliz/ControlLogoNet/README.md b/spaces/salahIguiliz/ControlLogoNet/README.md deleted file mode 100644 index 5a5d9aa152f027e433be3938b59dd17379d6d5da..0000000000000000000000000000000000000000 --- a/spaces/salahIguiliz/ControlLogoNet/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Control Logo Net -emoji: 🖌️ -colorFrom: indigo -colorTo: indigo -sdk: gradio -sdk_version: 3.20.1 -app_file: app.py -pinned: true ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/sbroy10/03-NLP-SOTA-MedEntity/README.md b/spaces/sbroy10/03-NLP-SOTA-MedEntity/README.md deleted file mode 100644 index d7d1a56bd0ba77d31544bf0db0a9ca5cb49ca45e..0000000000000000000000000000000000000000 --- a/spaces/sbroy10/03-NLP-SOTA-MedEntity/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 03 NLP SOTA MedEntity -emoji: ⚡ -colorFrom: blue -colorTo: green -sdk: gradio -sdk_version: 2.9.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/scedlatioru/img-to-music/example/Descargar Pro Tools 9 Portable Para Pc 1 Link Full LINK.md b/spaces/scedlatioru/img-to-music/example/Descargar Pro Tools 9 Portable Para Pc 1 Link Full LINK.md deleted file mode 100644 index d965eee9856d4efa5f44a3dac800d85d6bacf095..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/Descargar Pro Tools 9 Portable Para Pc 1 Link Full LINK.md +++ /dev/null @@ -1,25 +0,0 @@ - -

    How to Download Pro Tools 9 Portable for PC with One Link

    -

    Pro Tools 9 is a powerful audio editing software that allows you to create, record, mix and master professional-quality music and sound. However, installing Pro Tools 9 on your PC can be a hassle, especially if you don't have enough disk space or a fast internet connection. That's why some users prefer to download Pro Tools 9 Portable, a version of the software that can run from a USB flash drive or an external hard drive without installation.

    -

    In this article, we will show you how to download Pro Tools 9 Portable for PC with one link, so you can enjoy the benefits of this software without any complications. Here are the steps you need to follow:

    -

    descargar pro tools 9 portable para pc 1 link full


    Download Ziphttps://gohhs.com/2uEzhb



    -
      -
    1. Go to this website [^1^] and click on the green button that says "Download Now". This will take you to a page where you can choose between different download options.
    2. -
    3. Select the option that says "Pro Tools 9 Portable (1 Link)". This will start the download of a compressed file that contains the portable version of Pro Tools 9.
    4. -
    5. Once the download is complete, extract the compressed file to a folder on your PC or on your USB flash drive or external hard drive. You can use any program that can handle ZIP or RAR files, such as WinRAR or 7-Zip.
    6. -
    7. Open the folder where you extracted the file and double-click on the file that says "ProTools.exe". This will launch Pro Tools 9 Portable on your PC.
    8. -
    9. Enjoy using Pro Tools 9 Portable for your audio editing needs. You can create new projects, open existing ones, import audio files, apply effects, edit tracks, mix and export your work.
    10. -
    -

    Note: Pro Tools 9 Portable may not work on some PCs due to compatibility issues. If you encounter any problems, you can try downloading a different version of Pro Tools 9 Portable from this website [^2^] or this website [^3^]. However, we cannot guarantee the safety or quality of these downloads, so use them at your own risk.

    Pro Tools 9 Portable is a convenient way to use Pro Tools 9 without installation, but it also has some limitations and drawbacks. For example, Pro Tools 9 Portable may not be compatible with some plugins or hardware devices that require installation or authorization. Also, Pro Tools 9 Portable may not have the latest updates or features that are available in the official version of Pro Tools 9.

    -

    If you want to get the most out of Pro Tools 9, you may want to consider installing the official version of the software on your PC. This will allow you to access all the functions and capabilities of Pro Tools 9, as well as receive regular updates and support from Avid, the developer of Pro Tools. To install Pro Tools 9 on your PC, you will need to purchase a license from Avid or an authorized reseller. You will also need to meet the minimum system requirements for Pro Tools 9, which are:

    -
      -
    • Windows 7 (32-bit or 64-bit)
    • -
    • Intel Core 2 Duo processor or higher
    • -
    • 4 GB of RAM or more
    • -
    • 15 GB of free disk space or more
    • -
    • A compatible audio interface or sound card
    • -
    • An iLok USB key for authorization
    • -
    -

    Once you have the license and the system requirements, you can download the installer for Pro Tools 9 from Avid's website and follow the instructions to install it on your PC. You will also need to activate your license using the iLok USB key and register your product with Avid.

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/scedlatioru/img-to-music/example/Echo A1 Methode De Francais Answer Key Rapidshare.md b/spaces/scedlatioru/img-to-music/example/Echo A1 Methode De Francais Answer Key Rapidshare.md deleted file mode 100644 index 68db09171d1b732d1a0568a5d745da888a19eaf0..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/Echo A1 Methode De Francais Answer Key Rapidshare.md +++ /dev/null @@ -1,7 +0,0 @@ -

    echo a1 methode de francais answer key rapidshare


    DOWNLOAD ✫✫✫ https://gohhs.com/2uEyPI



    - -March 22, 2557 BC - The Workbook app contains all interactive self-study activities. Access to self-correction, evaluation, and answer keys is available depending on the type... At the time of writing the first volume (April 2008), all three modules of the application are in development. -There are also versions for Mac, Linux, Windows, Android and iOS (with the ability to install on a tablet): 8a78ff9644
    -
    -
    -

    diff --git a/spaces/shivambhosale/spacenet3-unet-1024-1024/README.md b/spaces/shivambhosale/spacenet3-unet-1024-1024/README.md deleted file mode 100644 index ceb1b4dc66dc5c21de44d8049e5af8a72d5c38af..0000000000000000000000000000000000000000 --- a/spaces/shivambhosale/spacenet3-unet-1024-1024/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Unet -emoji: 😻 -colorFrom: pink -colorTo: blue -sdk: gradio -sdk_version: 3.0.24 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/silk-road/ChatHaruhi/app_withAudio.py b/spaces/silk-road/ChatHaruhi/app_withAudio.py deleted file mode 100644 index d34398185445cec7fa37b88296696a5b5cdd2fe2..0000000000000000000000000000000000000000 --- a/spaces/silk-road/ChatHaruhi/app_withAudio.py +++ /dev/null @@ -1,417 +0,0 @@ -import os -os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 指定要使用的GPU设备编号 -from transformers import pipeline -import argparse -import openai -import tiktoken -import torch -from scipy.spatial.distance import cosine -from transformers import AutoModel, AutoTokenizer -from argparse import Namespace -from langchain.chat_models import ChatOpenAI -import gradio as gr -import random -import time -from langchain.prompts.chat import ( - ChatPromptTemplate, - SystemMessagePromptTemplate, - AIMessagePromptTemplate, - HumanMessagePromptTemplate, -) -from langchain.schema import ( - AIMessage, - HumanMessage, - SystemMessage -) -from text import Text - -def download_models(): - # Import our models. The package will take care of downloading the models automatically - model_args = Namespace(do_mlm=None, pooler_type="cls", temp=0.05, mlp_only_train=False, - init_embeddings_model=None) - model = AutoModel.from_pretrained("silk-road/luotuo-bert", trust_remote_code=True, model_args=model_args) - return model - -# OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY2") -# openai.api_key = 'sk-DfFyRKch' # 在这里输入你的OpenAI API Token - -# os.environ["OPENAI_API_KEY"] = openai.api_key - -folder_name = "Suzumiya" -current_directory = os.getcwd() -new_directory = os.path.join(current_directory, folder_name) - - -pkl_path = './pkl/texts.pkl' -text_image_pkl_path='./pkl/text_image.pkl' -dict_path = "../characters/haruhi/text_image_dict.txt" -dict_text_pkl_path = './pkl/dict_text.pkl' - -image_path = "../characters/haruhi/images" -model = download_models() -text = Text("../characters/haruhi/texts", text_image_pkl_path=text_image_pkl_path, - dict_text_pkl_path=dict_text_pkl_path, model=model, num_steps=50, pkl_path=pkl_path, - dict_path=dict_path, image_path=image_path) - -if not os.path.exists(new_directory): - os.makedirs(new_directory) - print(f"文件夹 '{folder_name}' 创建成功!") -else: - print(f"文件夹 '{folder_name}' 已经存在。") - -enc = tiktoken.get_encoding("cl100k_base") - - -class Run: - def __init__(self, **params): - """ - * 命令行参数的接入 - * 台词folder,记录台词 - * system prompt存成txt文件,支持切换 - * 支持设定max_len_story 和max_len_history - * 支持设定save_path - * 实现一个colab脚本,可以clone转换后的项目并运行,方便其他用户体验 - """ - self.folder = params['folder'] - # self.system_prompt = params['system_prompt'] - with open(params['system_prompt'], 'r') as f: - self.system_prompt = f.read() - self.max_len_story = params['max_len_story'] - self.max_len_history = params['max_len_history'] - self.save_path = params['save_path'] - self.titles, self.title_to_text = self.read_prompt_data() - self.embeddings, self.embed_to_title = self.title_text_embedding(self.titles, self.title_to_text) - # self.embeddings, self.embed_to_title = [], [] - # 一个封装 OpenAI 接口的函数,参数为 Prompt,返回对应结果 - - def get_completion_from_messages(self, messages, model="gpt-3.5-turbo", temperature=0): - response = openai.ChatCompletion.create( - model=model, - messages=messages, - temperature=temperature, # 控制模型输出的随机程度 - ) - # print(str(response.choices[0].message)) - return response.choices[0].message["content"] - - def read_prompt_data(self): - """ - read prompt-data for in-context-learning - """ - titles = [] - title_to_text = {} - for file in os.listdir(self.folder): - if file.endswith('.txt'): - title_name = file[:-4] - titles.append(title_name) - - with open(os.path.join(self.folder, file), 'r') as f: - title_to_text[title_name] = f.read() - - return titles, title_to_text - - - def get_embedding(self, text): - tokenizer = AutoTokenizer.from_pretrained("silk-road/luotuo-bert") - model = download_models() - if len(text) > 512: - text = text[:512] - texts = [text] - # Tokenize the text - inputs = tokenizer(texts, padding=True, truncation=False, return_tensors="pt") - # Extract the embeddings - # Get the embeddings - with torch.no_grad(): - embeddings = model(**inputs, output_hidden_states=True, return_dict=True, sent_emb=True).pooler_output - return embeddings[0] - - def title_text_embedding(self, titles, title_to_text): - """titles-text-embeddings""" - - embeddings = [] - embed_to_title = [] - - for title in titles: - text = title_to_text[title] - - # divide text with \n\n - divided_texts = text.split('\n\n') - - for divided_text in divided_texts: - embed = self.get_embedding(divided_text) - embeddings.append(embed) - embed_to_title.append(title) - - return embeddings, embed_to_title - - def get_cosine_similarity(self, embed1, embed2): - return torch.nn.functional.cosine_similarity(embed1, embed2, dim=0) - - def retrieve_title(self, query_embed, embeddings, embed_to_title, k): - # compute cosine similarity between query_embed and embeddings - cosine_similarities = [] - for embed in embeddings: - cosine_similarities.append(self.get_cosine_similarity(query_embed, embed)) - - # sort cosine similarity - sorted_cosine_similarities = sorted(cosine_similarities, reverse=True) - - top_k_index = [] - top_k_title = [] - - for i in range(len(sorted_cosine_similarities)): - current_title = embed_to_title[cosine_similarities.index(sorted_cosine_similarities[i])] - if current_title not in top_k_title: - top_k_title.append(current_title) - top_k_index.append(cosine_similarities.index(sorted_cosine_similarities[i])) - - if len(top_k_title) == k: - break - - return top_k_title - - def organize_story_with_maxlen(self, selected_sample): - maxlen = self.max_len_story - # title_to_text, _ = self.read_prompt_data() - story = "凉宫春日的经典桥段如下:\n" - - count = 0 - - final_selected = [] - print(selected_sample) - for sample_topic in selected_sample: - # find sample_answer in dictionary - sample_story = self.title_to_text[sample_topic] - - sample_len = len(enc.encode(sample_story)) - # print(sample_topic, ' ' , sample_len) - if sample_len + count > maxlen: - break - - story += sample_story - story += '\n' - - count += sample_len - final_selected.append(sample_topic) - - return story, final_selected - - def organize_message(self, story, history_chat, history_response, new_query): - messages = [{'role': 'system', 'content': self.system_prompt}, {'role': 'user', 'content': story}] - - n = len(history_chat) - if n != len(history_response): - print('warning, unmatched history_char length, clean and start new chat') - # clean all - history_chat = [] - history_response = [] - n = 0 - - for i in range(n): - messages.append({'role': 'user', 'content': history_chat[i]}) - messages.append({'role': 'user', 'content': history_response[i]}) - - messages.append({'role': 'user', 'content': new_query}) - - return messages - - def keep_tail(self, history_chat, history_response): - max_len = self.max_len_history - n = len(history_chat) - if n == 0: - return [], [] - - if n != len(history_response): - print('warning, unmatched history_char length, clean and start new chat') - return [], [] - - token_len = [] - for i in range(n): - chat_len = len(enc.encode(history_chat[i])) - res_len = len(enc.encode(history_response[i])) - token_len.append(chat_len + res_len) - - keep_k = 1 - count = token_len[n - 1] - - for i in range(1, n): - count += token_len[n - 1 - i] - if count > max_len: - break - keep_k += 1 - - return history_chat[-keep_k:], history_response[-keep_k:] - - def organize_message_langchain(self, story, history_chat, history_response, new_query): - # messages = [{'role':'system', 'content':SYSTEM_PROMPT}, {'role':'user', 'content':story}] - - messages = [ - SystemMessage(content=self.system_prompt), - HumanMessage(content=story) - ] - - n = len(history_chat) - if n != len(history_response): - print('warning, unmatched history_char length, clean and start new chat') - # clean all - history_chat = [] - history_response = [] - n = 0 - - for i in range(n): - messages.append(HumanMessage(content=history_chat[i])) - messages.append(AIMessage(content=history_response[i])) - - # messages.append( {'role':'user', 'content':new_query }) - messages.append(HumanMessage(content=new_query)) - - return messages - - def get_response(self, user_message, chat_history_tuple): - - history_chat = [] - history_response = [] - - if len(chat_history_tuple) > 0: - for cha, res in chat_history_tuple: - history_chat.append(cha) - history_response.append(res) - - history_chat, history_response = self.keep_tail(history_chat, history_response) - - print('history done') - - new_query = user_message - query_embed = self.get_embedding(new_query) - - # print("1") - # embeddings, embed_to_title = self.title_text_embedding(self.titles, self.title_to_text) - - print("2") - selected_sample = self.retrieve_title(query_embed, self.embeddings, self.embed_to_title, 7) - - print("3") - story, selected_sample = self.organize_story_with_maxlen(selected_sample) - - ## TODO: visualize seletected sample later - print('当前辅助sample:', selected_sample) - - messages = self.organize_message_langchain(story, history_chat, history_response, new_query) - chat = ChatOpenAI(temperature=0) - return_msg = chat(messages) - - response = return_msg.content - - return response - - def save_response(self, chat_history_tuple): - with open(f"{self.save_path}/conversation_{time.time()}.txt", "w") as file: - for cha, res in chat_history_tuple: - file.write(cha) - file.write("\n---\n") - file.write(res) - file.write("\n---\n") - - def create_gradio(self): - # from google.colab import drive - # drive.mount(drive_path) - with gr.Blocks() as demo: - gr.Markdown( - """ - ## Chat凉宫春日 ChatHaruhi - 此版本为测试版本,非正式版本,正式版本功能更多,敬请期待 - """ - ) - image_input = gr.Textbox(visible=False) - japanese_input = gr.Textbox(visible=False) - with gr.Row(): - chatbot = gr.Chatbot() - image_output = gr.Image() - role_name = gr.Textbox(label="角色名", placeholde="输入角色名") - msg = gr.Textbox(label="输入") - with gr.Row(): - clear = gr.Button("Clear") - sub = gr.Button("Submit") - image_button = gr.Button("给我一个图") - japanese_output = gr.Textbox(interactive=False) - - - def respond(role_name, user_message, chat_history): - input_message = role_name + ':「' + user_message + '」' - bot_message = self.get_response(input_message, chat_history) - chat_history.append((input_message, bot_message)) - self.save_response(chat_history) - # time.sleep(1) - jp_text = pipe(f'<-zh2ja-> {bot_message}')[0]['translation_text'] - return "" , chat_history, bot_message, jp_text - - clear.click(lambda: None, None, chatbot, queue=False) - msg.submit(respond, [role_name, msg, chatbot], [msg, chatbot, image_input, japanese_output]) - sub.click(fn=respond, inputs=[role_name, msg, chatbot], outputs=[msg, chatbot, image_input, japanese_output]) - # with gr.Tab("text_to_text"): - # text_input = gr.Textbox() - # text_output = gr.Textbox() - # text_button = gr.Button('begin') - - # text_button.click(text.text_to_text, inputs=text_input, outputs=text_output) - - - - # with gr.Tab("text_to_iamge"): - # with gr.Row(): - # image_input = gr.Textbox() - # image_output = gr.Image() - # image_button = gr.Button("给我一个图") - - image_button.click(text.text_to_image, inputs=image_input, outputs=image_output) - - demo.launch(debug=True,share=True) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description="-----[Chat凉宫春日]-----") - parser.add_argument("--folder", default="../characters/haruhi/texts", help="text folder") - parser.add_argument("--system_prompt", default="../characters/haruhi/system_prompt.txt", help="store system_prompt") - parser.add_argument("--max_len_story", default=1500, type=int) - parser.add_argument("--max_len_history", default=1200, type=int) - # parser.add_argument("--save_path", default="/content/drive/MyDrive/GPTData/Haruhi-Lulu/") - parser.add_argument("--save_path", default=os.getcwd()+"/Suzumiya") - options = parser.parse_args() - params = { - "folder": options.folder, - "system_prompt": options.system_prompt, - "max_len_story": options.max_len_story, - "max_len_history": options.max_len_history, - "save_path": options.save_path - } - pipe = pipeline(model="engmatic-earth/mt5-zh-ja-en-trimmed-fine-tuned-v1", device=0,max_length=120) - run = Run(**params) - run.create_gradio() - - - # history_chat = [] - # history_response = [] - # chat_timer = 5 - # new_query = '鲁鲁:你好我是新同学鲁鲁' - - # query_embed = run.get_embedding(new_query) - # titles, title_to_text = run.read_prompt_data() - # embeddings, embed_to_title = run.title_text_embedding(titles, title_to_text) - # selected_sample = run.retrieve_title(query_embed, embeddings, embed_to_title, 7) - - # print('限制长度之前:', selected_sample) - - # story, selected_sample = run.organize_story_with_maxlen(selected_sample) - - # print('当前辅助sample:', selected_sample) - - # messages = run.organize_message(story, history_chat, history_response, new_query) - - # response = run.get_completion_from_messages(messages) - - # print(response) - - # history_chat.append(new_query) - # history_response.append(response) - - # history_chat, history_response = run.keep_tail(history_chat, history_response) - # print(history_chat, history_response) diff --git a/spaces/simpie28/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c b/spaces/simpie28/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c deleted file mode 100644 index 5631d20a9a00db29e143a6e8e4e5c378d6bb850a..0000000000000000000000000000000000000000 --- a/spaces/simpie28/VITS-Umamusume-voice-synthesizer/monotonic_align/core.c +++ /dev/null @@ -1,21299 +0,0 @@ -/* Generated by Cython 0.29.21 */ - -/* BEGIN: Cython Metadata -{ - "distutils": { - "name": "monotonic_align.core", - "sources": [ - "core.pyx" - ] - }, - "module_name": "monotonic_align.core" -} -END: Cython Metadata */ - -#define PY_SSIZE_T_CLEAN -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_21" -#define CYTHON_HEX_VERSION 0x001D15F0 -#define CYTHON_FUTURE_DIVISION 0 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__monotonic_align__core -#define __PYX_HAVE_API__monotonic_align__core -/* Early includes */ -#include "pythread.h" -#include -#include -#include -#include "pystate.h" -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "core.pyx", - "stringsource", -}; -/* NoFastGil.proto */ -#define __Pyx_PyGILState_Ensure PyGILState_Ensure -#define __Pyx_PyGILState_Release PyGILState_Release -#define __Pyx_FastGIL_Remember() -#define __Pyx_FastGIL_Forget() -#define __Pyx_FastGilFuncInit() - -/* MemviewSliceStruct.proto */ -struct __pyx_memoryview_obj; -typedef struct { - struct __pyx_memoryview_obj *memview; - char *data; - Py_ssize_t shape[8]; - Py_ssize_t strides[8]; - Py_ssize_t suboffsets[8]; -} __Pyx_memviewslice; -#define __Pyx_MemoryView_Len(m) (m.shape[0]) - -/* Atomics.proto */ -#include -#ifndef CYTHON_ATOMICS - #define CYTHON_ATOMICS 1 -#endif -#define __pyx_atomic_int_type int -#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ - (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ - !defined(__i386__) - #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) - #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using GNU atomics" - #endif -#elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 - #include - #undef __pyx_atomic_int_type - #define __pyx_atomic_int_type LONG - #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) - #ifdef __PYX_DEBUG_ATOMICS - #pragma message ("Using MSVC atomics") - #endif -#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 - #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using Intel atomics" - #endif -#else - #undef CYTHON_ATOMICS - #define CYTHON_ATOMICS 0 - #ifdef __PYX_DEBUG_ATOMICS - #warning "Not using atomics" - #endif -#endif -typedef volatile __pyx_atomic_int_type __pyx_atomic_int; -#if CYTHON_ATOMICS - #define __pyx_add_acquisition_count(memview)\ - __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) -#else - #define __pyx_add_acquisition_count(memview)\ - __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) -#endif - -/* ForceInitThreads.proto */ -#ifndef __PYX_FORCE_INIT_THREADS - #define __PYX_FORCE_INIT_THREADS 0 -#endif - -/* BufferFormatStructs.proto */ -#define IS_UNSIGNED(type) (((type) -1) > 0) -struct __Pyx_StructField_; -#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) -typedef struct { - const char* name; - struct __Pyx_StructField_* fields; - size_t size; - size_t arraysize[8]; - int ndim; - char typegroup; - char is_unsigned; - int flags; -} __Pyx_TypeInfo; -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - size_t struct_alignment; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; - char is_valid_array; -} __Pyx_BufFmt_Context; - - -/*--- Type declarations ---*/ -struct __pyx_array_obj; -struct __pyx_MemviewEnum_obj; -struct __pyx_memoryview_obj; -struct __pyx_memoryviewslice_obj; -struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each; - -/* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ -struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each { - int __pyx_n; - float max_neg_val; -}; - -/* "View.MemoryView":105 - * - * @cname("__pyx_array") - * cdef class array: # <<<<<<<<<<<<<< - * - * cdef: - */ -struct __pyx_array_obj { - PyObject_HEAD - struct __pyx_vtabstruct_array *__pyx_vtab; - char *data; - Py_ssize_t len; - char *format; - int ndim; - Py_ssize_t *_shape; - Py_ssize_t *_strides; - Py_ssize_t itemsize; - PyObject *mode; - PyObject *_format; - void (*callback_free_data)(void *); - int free_data; - int dtype_is_object; -}; - - -/* "View.MemoryView":279 - * - * @cname('__pyx_MemviewEnum') - * cdef class Enum(object): # <<<<<<<<<<<<<< - * cdef object name - * def __init__(self, name): - */ -struct __pyx_MemviewEnum_obj { - PyObject_HEAD - PyObject *name; -}; - - -/* "View.MemoryView":330 - * - * @cname('__pyx_memoryview') - * cdef class memoryview(object): # <<<<<<<<<<<<<< - * - * cdef object obj - */ -struct __pyx_memoryview_obj { - PyObject_HEAD - struct __pyx_vtabstruct_memoryview *__pyx_vtab; - PyObject *obj; - PyObject *_size; - PyObject *_array_interface; - PyThread_type_lock lock; - __pyx_atomic_int acquisition_count[2]; - __pyx_atomic_int *acquisition_count_aligned_p; - Py_buffer view; - int flags; - int dtype_is_object; - __Pyx_TypeInfo *typeinfo; -}; - - -/* "View.MemoryView":965 - * - * @cname('__pyx_memoryviewslice') - * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< - * "Internal class for passing memoryview slices to Python" - * - */ -struct __pyx_memoryviewslice_obj { - struct __pyx_memoryview_obj __pyx_base; - __Pyx_memviewslice from_slice; - PyObject *from_object; - PyObject *(*to_object_func)(char *); - int (*to_dtype_func)(char *, PyObject *); -}; - - - -/* "View.MemoryView":105 - * - * @cname("__pyx_array") - * cdef class array: # <<<<<<<<<<<<<< - * - * cdef: - */ - -struct __pyx_vtabstruct_array { - PyObject *(*get_memview)(struct __pyx_array_obj *); -}; -static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; - - -/* "View.MemoryView":330 - * - * @cname('__pyx_memoryview') - * cdef class memoryview(object): # <<<<<<<<<<<<<< - * - * cdef object obj - */ - -struct __pyx_vtabstruct_memoryview { - char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); - PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); - PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); - PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); -}; -static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; - - -/* "View.MemoryView":965 - * - * @cname('__pyx_memoryviewslice') - * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< - * "Internal class for passing memoryview slices to Python" - * - */ - -struct __pyx_vtabstruct__memoryviewslice { - struct __pyx_vtabstruct_memoryview __pyx_base; -}; -static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* MemviewSliceInit.proto */ -#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d -#define __Pyx_MEMVIEW_DIRECT 1 -#define __Pyx_MEMVIEW_PTR 2 -#define __Pyx_MEMVIEW_FULL 4 -#define __Pyx_MEMVIEW_CONTIG 8 -#define __Pyx_MEMVIEW_STRIDED 16 -#define __Pyx_MEMVIEW_FOLLOW 32 -#define __Pyx_IS_C_CONTIG 1 -#define __Pyx_IS_F_CONTIG 2 -static int __Pyx_init_memviewslice( - struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference); -static CYTHON_INLINE int __pyx_add_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) -#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) -#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) -#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) -static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* None.proto */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); - -/* ArgTypeTest.proto */ -#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ - ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ - __Pyx__ArgTypeTest(obj, type, name, exact)) -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* IncludeStringH.proto */ -#include - -/* BytesEquals.proto */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -/* UnicodeEquals.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -/* StrEquals.proto */ -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif - -/* None.proto */ -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); - -/* UnaryNegOverflows.proto */ -#define UNARY_NEG_WOULD_OVERFLOW(x)\ - (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) - -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ -/* GetAttr.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); - -/* GetItemInt.proto */ -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/* ObjectGetItem.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); -#else -#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) -#endif - -/* decode_c_string_utf16.proto */ -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 0; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = -1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} - -/* decode_c_string.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/* PyErrExceptionMatches.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) -static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); -#else -#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) -#endif - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* ExtTypeTest.proto */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* SwapException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -/* ListCompAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len)) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) -#endif - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) -#endif - -/* ListExtend.proto */ -static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject* none = _PyList_Extend((PyListObject*)L, v); - if (unlikely(!none)) - return -1; - Py_DECREF(none); - return 0; -#else - return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); -#endif -} - -/* ListAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -/* None.proto */ -static CYTHON_INLINE long __Pyx_div_long(long, long); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* HasAttr.proto */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); - -/* PyObject_GenericGetAttrNoDict.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr -#endif - -/* PyObject_GenericGetAttr.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr -#endif - -/* SetVTable.proto */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable); - -/* PyObjectGetAttrStrNoError.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); - -/* SetupReduce.proto */ -static int __Pyx_setup_reduce(PyObject* type_obj); - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -#if PY_MAJOR_VERSION < 3 - static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); - static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else - #define __Pyx_GetBuffer PyObject_GetBuffer - #define __Pyx_ReleaseBuffer PyBuffer_Release -#endif - - -/* BufferStructDeclare.proto */ -typedef struct { - Py_ssize_t shape, strides, suboffsets; -} __Pyx_Buf_DimInfo; -typedef struct { - size_t refcount; - Py_buffer pybuffer; -} __Pyx_Buffer; -typedef struct { - __Pyx_Buffer *rcbuffer; - char *data; - __Pyx_Buf_DimInfo diminfo[8]; -} __Pyx_LocalBuf_ND; - -/* MemviewSliceIsContig.proto */ -static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); - -/* OverlappingSlices.proto */ -static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize); - -/* Capsule.proto */ -static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); - -/* IsLittleEndian.proto */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); - -/* BufferFormatCheck.proto */ -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type); - -/* TypeInfoCompare.proto */ -static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); - -/* MemviewSliceValidateAndInit.proto */ -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *, int writable_flag); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* MemviewSliceCopyTemplate.proto */ -static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ -static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ -static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ -static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ -static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ -static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ - -/* Module declarations from 'cython.view' */ - -/* Module declarations from 'cython' */ - -/* Module declarations from 'monotonic_align.core' */ -static PyTypeObject *__pyx_array_type = 0; -static PyTypeObject *__pyx_MemviewEnum_type = 0; -static PyTypeObject *__pyx_memoryview_type = 0; -static PyTypeObject *__pyx_memoryviewslice_type = 0; -static PyObject *generic = 0; -static PyObject *strided = 0; -static PyObject *indirect = 0; -static PyObject *contiguous = 0; -static PyObject *indirect_contiguous = 0; -static int __pyx_memoryview_thread_locks_used; -static PyThread_type_lock __pyx_memoryview_thread_locks[8]; -static void __pyx_f_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice, __Pyx_memviewslice, int, int, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each *__pyx_optional_args); /*proto*/ -static void __pyx_f_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ -static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ -static void *__pyx_align_pointer(void *, size_t); /*proto*/ -static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ -static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ -static PyObject *_unellipsify(PyObject *, int); /*proto*/ -static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ -static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ -static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ -static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ -static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ -static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ -static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ -static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ -static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ -static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ -static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ -static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ -static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ -static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ -static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ -static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ -static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ -static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ -static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ -static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ -static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ -static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ -static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 }; -#define __Pyx_MODULE_NAME "monotonic_align.core" -extern int __pyx_module_is_main_monotonic_align__core; -int __pyx_module_is_main_monotonic_align__core = 0; - -/* Implementation of 'monotonic_align.core' */ -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_MemoryError; -static PyObject *__pyx_builtin_enumerate; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_Ellipsis; -static PyObject *__pyx_builtin_id; -static PyObject *__pyx_builtin_IndexError; -static const char __pyx_k_O[] = "O"; -static const char __pyx_k_c[] = "c"; -static const char __pyx_k_id[] = "id"; -static const char __pyx_k_new[] = "__new__"; -static const char __pyx_k_obj[] = "obj"; -static const char __pyx_k_base[] = "base"; -static const char __pyx_k_dict[] = "__dict__"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_mode[] = "mode"; -static const char __pyx_k_name[] = "name"; -static const char __pyx_k_ndim[] = "ndim"; -static const char __pyx_k_pack[] = "pack"; -static const char __pyx_k_size[] = "size"; -static const char __pyx_k_step[] = "step"; -static const char __pyx_k_stop[] = "stop"; -static const char __pyx_k_t_xs[] = "t_xs"; -static const char __pyx_k_t_ys[] = "t_ys"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_ASCII[] = "ASCII"; -static const char __pyx_k_class[] = "__class__"; -static const char __pyx_k_error[] = "error"; -static const char __pyx_k_flags[] = "flags"; -static const char __pyx_k_paths[] = "paths"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_shape[] = "shape"; -static const char __pyx_k_start[] = "start"; -static const char __pyx_k_encode[] = "encode"; -static const char __pyx_k_format[] = "format"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_name_2[] = "__name__"; -static const char __pyx_k_pickle[] = "pickle"; -static const char __pyx_k_reduce[] = "__reduce__"; -static const char __pyx_k_struct[] = "struct"; -static const char __pyx_k_unpack[] = "unpack"; -static const char __pyx_k_update[] = "update"; -static const char __pyx_k_values[] = "values"; -static const char __pyx_k_fortran[] = "fortran"; -static const char __pyx_k_memview[] = "memview"; -static const char __pyx_k_Ellipsis[] = "Ellipsis"; -static const char __pyx_k_getstate[] = "__getstate__"; -static const char __pyx_k_itemsize[] = "itemsize"; -static const char __pyx_k_pyx_type[] = "__pyx_type"; -static const char __pyx_k_setstate[] = "__setstate__"; -static const char __pyx_k_TypeError[] = "TypeError"; -static const char __pyx_k_enumerate[] = "enumerate"; -static const char __pyx_k_pyx_state[] = "__pyx_state"; -static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; -static const char __pyx_k_IndexError[] = "IndexError"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_pyx_result[] = "__pyx_result"; -static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static const char __pyx_k_MemoryError[] = "MemoryError"; -static const char __pyx_k_PickleError[] = "PickleError"; -static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; -static const char __pyx_k_stringsource[] = "stringsource"; -static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; -static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; -static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; -static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; -static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; -static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; -static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; -static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_strided_and_direct[] = ""; -static const char __pyx_k_strided_and_indirect[] = ""; -static const char __pyx_k_contiguous_and_direct[] = ""; -static const char __pyx_k_MemoryView_of_r_object[] = ""; -static const char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; -static const char __pyx_k_contiguous_and_indirect[] = ""; -static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; -static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; -static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; -static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; -static const char __pyx_k_strided_and_direct_or_indirect[] = ""; -static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; -static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; -static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; -static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; -static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; -static const char __pyx_k_Incompatible_checksums_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (name))"; -static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; -static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; -static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; -static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; -static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; -static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; -static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; -static PyObject *__pyx_n_s_ASCII; -static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; -static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; -static PyObject *__pyx_kp_s_Cannot_assign_to_read_only_memor; -static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; -static PyObject *__pyx_kp_s_Cannot_index_with_type_s; -static PyObject *__pyx_n_s_Ellipsis; -static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; -static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; -static PyObject *__pyx_n_s_IndexError; -static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; -static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; -static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; -static PyObject *__pyx_n_s_MemoryError; -static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; -static PyObject *__pyx_kp_s_MemoryView_of_r_object; -static PyObject *__pyx_n_b_O; -static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; -static PyObject *__pyx_n_s_PickleError; -static PyObject *__pyx_n_s_TypeError; -static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; -static PyObject *__pyx_n_s_ValueError; -static PyObject *__pyx_n_s_View_MemoryView; -static PyObject *__pyx_n_s_allocate_buffer; -static PyObject *__pyx_n_s_base; -static PyObject *__pyx_n_s_c; -static PyObject *__pyx_n_u_c; -static PyObject *__pyx_n_s_class; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_kp_s_contiguous_and_direct; -static PyObject *__pyx_kp_s_contiguous_and_indirect; -static PyObject *__pyx_n_s_dict; -static PyObject *__pyx_n_s_dtype_is_object; -static PyObject *__pyx_n_s_encode; -static PyObject *__pyx_n_s_enumerate; -static PyObject *__pyx_n_s_error; -static PyObject *__pyx_n_s_flags; -static PyObject *__pyx_n_s_format; -static PyObject *__pyx_n_s_fortran; -static PyObject *__pyx_n_u_fortran; -static PyObject *__pyx_n_s_getstate; -static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; -static PyObject *__pyx_n_s_id; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_itemsize; -static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_memview; -static PyObject *__pyx_n_s_mode; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_name_2; -static PyObject *__pyx_n_s_ndim; -static PyObject *__pyx_n_s_new; -static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; -static PyObject *__pyx_n_s_obj; -static PyObject *__pyx_n_s_pack; -static PyObject *__pyx_n_s_paths; -static PyObject *__pyx_n_s_pickle; -static PyObject *__pyx_n_s_pyx_PickleError; -static PyObject *__pyx_n_s_pyx_checksum; -static PyObject *__pyx_n_s_pyx_getbuffer; -static PyObject *__pyx_n_s_pyx_result; -static PyObject *__pyx_n_s_pyx_state; -static PyObject *__pyx_n_s_pyx_type; -static PyObject *__pyx_n_s_pyx_unpickle_Enum; -static PyObject *__pyx_n_s_pyx_vtable; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_reduce; -static PyObject *__pyx_n_s_reduce_cython; -static PyObject *__pyx_n_s_reduce_ex; -static PyObject *__pyx_n_s_setstate; -static PyObject *__pyx_n_s_setstate_cython; -static PyObject *__pyx_n_s_shape; -static PyObject *__pyx_n_s_size; -static PyObject *__pyx_n_s_start; -static PyObject *__pyx_n_s_step; -static PyObject *__pyx_n_s_stop; -static PyObject *__pyx_kp_s_strided_and_direct; -static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; -static PyObject *__pyx_kp_s_strided_and_indirect; -static PyObject *__pyx_kp_s_stringsource; -static PyObject *__pyx_n_s_struct; -static PyObject *__pyx_n_s_t_xs; -static PyObject *__pyx_n_s_t_ys; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_kp_s_unable_to_allocate_array_data; -static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; -static PyObject *__pyx_n_s_unpack; -static PyObject *__pyx_n_s_update; -static PyObject *__pyx_n_s_values; -static PyObject *__pyx_pf_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ -static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ -static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_184977713; -static PyObject *__pyx_int_neg_1; -static float __pyx_k_; -static PyObject *__pyx_tuple__2; -static PyObject *__pyx_tuple__3; -static PyObject *__pyx_tuple__4; -static PyObject *__pyx_tuple__5; -static PyObject *__pyx_tuple__6; -static PyObject *__pyx_tuple__7; -static PyObject *__pyx_tuple__8; -static PyObject *__pyx_tuple__9; -static PyObject *__pyx_slice__16; -static PyObject *__pyx_tuple__10; -static PyObject *__pyx_tuple__11; -static PyObject *__pyx_tuple__12; -static PyObject *__pyx_tuple__13; -static PyObject *__pyx_tuple__14; -static PyObject *__pyx_tuple__15; -static PyObject *__pyx_tuple__17; -static PyObject *__pyx_tuple__18; -static PyObject *__pyx_tuple__19; -static PyObject *__pyx_tuple__20; -static PyObject *__pyx_tuple__21; -static PyObject *__pyx_tuple__22; -static PyObject *__pyx_tuple__23; -static PyObject *__pyx_tuple__24; -static PyObject *__pyx_tuple__25; -static PyObject *__pyx_codeobj__26; -/* Late includes */ - -/* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ - -static void __pyx_f_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice __pyx_v_path, __Pyx_memviewslice __pyx_v_value, int __pyx_v_t_y, int __pyx_v_t_x, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each *__pyx_optional_args) { - float __pyx_v_max_neg_val = __pyx_k_; - int __pyx_v_x; - int __pyx_v_y; - float __pyx_v_v_prev; - float __pyx_v_v_cur; - int __pyx_v_index; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - long __pyx_t_4; - int __pyx_t_5; - long __pyx_t_6; - long __pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - Py_ssize_t __pyx_t_10; - float __pyx_t_11; - float __pyx_t_12; - float __pyx_t_13; - int __pyx_t_14; - Py_ssize_t __pyx_t_15; - Py_ssize_t __pyx_t_16; - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_max_neg_val = __pyx_optional_args->max_neg_val; - } - } - - /* "monotonic_align/core.pyx":13 - * cdef float v_cur - * cdef float tmp - * cdef int index = t_x - 1 # <<<<<<<<<<<<<< - * - * for y in range(t_y): - */ - __pyx_v_index = (__pyx_v_t_x - 1); - - /* "monotonic_align/core.pyx":15 - * cdef int index = t_x - 1 - * - * for y in range(t_y): # <<<<<<<<<<<<<< - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: - */ - __pyx_t_1 = __pyx_v_t_y; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_y = __pyx_t_3; - - /* "monotonic_align/core.pyx":16 - * - * for y in range(t_y): - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): # <<<<<<<<<<<<<< - * if x == y: - * v_cur = max_neg_val - */ - __pyx_t_4 = (__pyx_v_y + 1); - __pyx_t_5 = __pyx_v_t_x; - if (((__pyx_t_4 < __pyx_t_5) != 0)) { - __pyx_t_6 = __pyx_t_4; - } else { - __pyx_t_6 = __pyx_t_5; - } - __pyx_t_4 = __pyx_t_6; - __pyx_t_5 = ((__pyx_v_t_x + __pyx_v_y) - __pyx_v_t_y); - __pyx_t_6 = 0; - if (((__pyx_t_5 > __pyx_t_6) != 0)) { - __pyx_t_7 = __pyx_t_5; - } else { - __pyx_t_7 = __pyx_t_6; - } - __pyx_t_6 = __pyx_t_4; - for (__pyx_t_5 = __pyx_t_7; __pyx_t_5 < __pyx_t_6; __pyx_t_5+=1) { - __pyx_v_x = __pyx_t_5; - - /* "monotonic_align/core.pyx":17 - * for y in range(t_y): - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: # <<<<<<<<<<<<<< - * v_cur = max_neg_val - * else: - */ - __pyx_t_8 = ((__pyx_v_x == __pyx_v_y) != 0); - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":18 - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: - * v_cur = max_neg_val # <<<<<<<<<<<<<< - * else: - * v_cur = value[y-1, x] - */ - __pyx_v_v_cur = __pyx_v_max_neg_val; - - /* "monotonic_align/core.pyx":17 - * for y in range(t_y): - * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): - * if x == y: # <<<<<<<<<<<<<< - * v_cur = max_neg_val - * else: - */ - goto __pyx_L7; - } - - /* "monotonic_align/core.pyx":20 - * v_cur = max_neg_val - * else: - * v_cur = value[y-1, x] # <<<<<<<<<<<<<< - * if x == 0: - * if y == 0: - */ - /*else*/ { - __pyx_t_9 = (__pyx_v_y - 1); - __pyx_t_10 = __pyx_v_x; - __pyx_v_v_cur = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))); - } - __pyx_L7:; - - /* "monotonic_align/core.pyx":21 - * else: - * v_cur = value[y-1, x] - * if x == 0: # <<<<<<<<<<<<<< - * if y == 0: - * v_prev = 0. - */ - __pyx_t_8 = ((__pyx_v_x == 0) != 0); - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":22 - * v_cur = value[y-1, x] - * if x == 0: - * if y == 0: # <<<<<<<<<<<<<< - * v_prev = 0. - * else: - */ - __pyx_t_8 = ((__pyx_v_y == 0) != 0); - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":23 - * if x == 0: - * if y == 0: - * v_prev = 0. # <<<<<<<<<<<<<< - * else: - * v_prev = max_neg_val - */ - __pyx_v_v_prev = 0.; - - /* "monotonic_align/core.pyx":22 - * v_cur = value[y-1, x] - * if x == 0: - * if y == 0: # <<<<<<<<<<<<<< - * v_prev = 0. - * else: - */ - goto __pyx_L9; - } - - /* "monotonic_align/core.pyx":25 - * v_prev = 0. - * else: - * v_prev = max_neg_val # <<<<<<<<<<<<<< - * else: - * v_prev = value[y-1, x-1] - */ - /*else*/ { - __pyx_v_v_prev = __pyx_v_max_neg_val; - } - __pyx_L9:; - - /* "monotonic_align/core.pyx":21 - * else: - * v_cur = value[y-1, x] - * if x == 0: # <<<<<<<<<<<<<< - * if y == 0: - * v_prev = 0. - */ - goto __pyx_L8; - } - - /* "monotonic_align/core.pyx":27 - * v_prev = max_neg_val - * else: - * v_prev = value[y-1, x-1] # <<<<<<<<<<<<<< - * value[y, x] += max(v_prev, v_cur) - * - */ - /*else*/ { - __pyx_t_10 = (__pyx_v_y - 1); - __pyx_t_9 = (__pyx_v_x - 1); - __pyx_v_v_prev = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_10 * __pyx_v_value.strides[0]) )) + __pyx_t_9)) ))); - } - __pyx_L8:; - - /* "monotonic_align/core.pyx":28 - * else: - * v_prev = value[y-1, x-1] - * value[y, x] += max(v_prev, v_cur) # <<<<<<<<<<<<<< - * - * for y in range(t_y - 1, -1, -1): - */ - __pyx_t_11 = __pyx_v_v_cur; - __pyx_t_12 = __pyx_v_v_prev; - if (((__pyx_t_11 > __pyx_t_12) != 0)) { - __pyx_t_13 = __pyx_t_11; - } else { - __pyx_t_13 = __pyx_t_12; - } - __pyx_t_9 = __pyx_v_y; - __pyx_t_10 = __pyx_v_x; - *((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) )) += __pyx_t_13; - } - } - - /* "monotonic_align/core.pyx":30 - * value[y, x] += max(v_prev, v_cur) - * - * for y in range(t_y - 1, -1, -1): # <<<<<<<<<<<<<< - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - */ - for (__pyx_t_1 = (__pyx_v_t_y - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_y = __pyx_t_1; - - /* "monotonic_align/core.pyx":31 - * - * for y in range(t_y - 1, -1, -1): - * path[y, index] = 1 # <<<<<<<<<<<<<< - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - * index = index - 1 - */ - __pyx_t_10 = __pyx_v_y; - __pyx_t_9 = __pyx_v_index; - *((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_path.data + __pyx_t_10 * __pyx_v_path.strides[0]) )) + __pyx_t_9)) )) = 1; - - /* "monotonic_align/core.pyx":32 - * for y in range(t_y - 1, -1, -1): - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): # <<<<<<<<<<<<<< - * index = index - 1 - * - */ - __pyx_t_14 = ((__pyx_v_index != 0) != 0); - if (__pyx_t_14) { - } else { - __pyx_t_8 = __pyx_t_14; - goto __pyx_L13_bool_binop_done; - } - __pyx_t_14 = ((__pyx_v_index == __pyx_v_y) != 0); - if (!__pyx_t_14) { - } else { - __pyx_t_8 = __pyx_t_14; - goto __pyx_L13_bool_binop_done; - } - __pyx_t_9 = (__pyx_v_y - 1); - __pyx_t_10 = __pyx_v_index; - __pyx_t_15 = (__pyx_v_y - 1); - __pyx_t_16 = (__pyx_v_index - 1); - __pyx_t_14 = (((*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))) < (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_15 * __pyx_v_value.strides[0]) )) + __pyx_t_16)) )))) != 0); - __pyx_t_8 = __pyx_t_14; - __pyx_L13_bool_binop_done:; - if (__pyx_t_8) { - - /* "monotonic_align/core.pyx":33 - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): - * index = index - 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_index = (__pyx_v_index - 1); - - /* "monotonic_align/core.pyx":32 - * for y in range(t_y - 1, -1, -1): - * path[y, index] = 1 - * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): # <<<<<<<<<<<<<< - * index = index - 1 - * - */ - } - } - - /* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ - - /* function exit code */ -} - -/* "monotonic_align/core.pyx":38 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: # <<<<<<<<<<<<<< - * cdef int b = paths.shape[0] - * cdef int i - */ - -static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static void __pyx_f_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs, CYTHON_UNUSED int __pyx_skip_dispatch) { - CYTHON_UNUSED int __pyx_v_b; - int __pyx_v_i; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; - Py_ssize_t __pyx_t_6; - Py_ssize_t __pyx_t_7; - - /* "monotonic_align/core.pyx":39 - * @cython.wraparound(False) - * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: - * cdef int b = paths.shape[0] # <<<<<<<<<<<<<< - * cdef int i - * for i in prange(b, nogil=True): - */ - __pyx_v_b = (__pyx_v_paths.shape[0]); - - /* "monotonic_align/core.pyx":41 - * cdef int b = paths.shape[0] - * cdef int i - * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< - * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) - */ - { - #ifdef WITH_THREAD - PyThreadState *_save; - Py_UNBLOCK_THREADS - __Pyx_FastGIL_Remember(); - #endif - /*try:*/ { - __pyx_t_1 = __pyx_v_b; - if ((1 == 0)) abort(); - { - #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) - #undef likely - #undef unlikely - #define likely(x) (x) - #define unlikely(x) (x) - #endif - __pyx_t_3 = (__pyx_t_1 - 0 + 1 - 1/abs(1)) / 1; - if (__pyx_t_3 > 0) - { - #ifdef _OPENMP - #pragma omp parallel private(__pyx_t_6, __pyx_t_7) firstprivate(__pyx_t_4, __pyx_t_5) - #endif /* _OPENMP */ - { - #ifdef _OPENMP - #pragma omp for firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) - #endif /* _OPENMP */ - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ - { - __pyx_v_i = (int)(0 + 1 * __pyx_t_2); - - /* "monotonic_align/core.pyx":42 - * cdef int i - * for i in prange(b, nogil=True): - * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) # <<<<<<<<<<<<<< - */ - __pyx_t_4.data = __pyx_v_paths.data; - __pyx_t_4.memview = __pyx_v_paths.memview; - __PYX_INC_MEMVIEW(&__pyx_t_4, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_i; - Py_ssize_t __pyx_tmp_stride = __pyx_v_paths.strides[0]; - __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_4.shape[0] = __pyx_v_paths.shape[1]; -__pyx_t_4.strides[0] = __pyx_v_paths.strides[1]; - __pyx_t_4.suboffsets[0] = -1; - -__pyx_t_4.shape[1] = __pyx_v_paths.shape[2]; -__pyx_t_4.strides[1] = __pyx_v_paths.strides[2]; - __pyx_t_4.suboffsets[1] = -1; - -__pyx_t_5.data = __pyx_v_values.data; - __pyx_t_5.memview = __pyx_v_values.memview; - __PYX_INC_MEMVIEW(&__pyx_t_5, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_i; - Py_ssize_t __pyx_tmp_stride = __pyx_v_values.strides[0]; - __pyx_t_5.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_5.shape[0] = __pyx_v_values.shape[1]; -__pyx_t_5.strides[0] = __pyx_v_values.strides[1]; - __pyx_t_5.suboffsets[0] = -1; - -__pyx_t_5.shape[1] = __pyx_v_values.shape[2]; -__pyx_t_5.strides[1] = __pyx_v_values.strides[2]; - __pyx_t_5.suboffsets[1] = -1; - -__pyx_t_6 = __pyx_v_i; - __pyx_t_7 = __pyx_v_i; - __pyx_f_15monotonic_align_4core_maximum_path_each(__pyx_t_4, __pyx_t_5, (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_ys.data) + __pyx_t_6)) ))), (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_xs.data) + __pyx_t_7)) ))), NULL); - __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); - __pyx_t_4.memview = NULL; - __pyx_t_4.data = NULL; - __PYX_XDEC_MEMVIEW(&__pyx_t_5, 0); - __pyx_t_5.memview = NULL; - __pyx_t_5.data = NULL; - } - } - } - } - } - #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) - #undef likely - #undef unlikely - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #endif - } - - /* "monotonic_align/core.pyx":41 - * cdef int b = paths.shape[0] - * cdef int i - * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< - * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) - */ - /*finally:*/ { - /*normal exit:*/{ - #ifdef WITH_THREAD - __Pyx_FastGIL_Forget(); - Py_BLOCK_THREADS - #endif - goto __pyx_L5; - } - __pyx_L5:; - } - } - - /* "monotonic_align/core.pyx":38 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: # <<<<<<<<<<<<<< - * cdef int b = paths.shape[0] - * cdef int i - */ - - /* function exit code */ -} - -/* Python wrapper */ -static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __Pyx_memviewslice __pyx_v_paths = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_values = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_t_ys = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_t_xs = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("maximum_path_c (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_paths,&__pyx_n_s_values,&__pyx_n_s_t_ys,&__pyx_n_s_t_xs,0}; - PyObject* values[4] = {0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_paths)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_values)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 1); __PYX_ERR(0, 38, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_ys)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 2); __PYX_ERR(0, 38, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_xs)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 3); __PYX_ERR(0, 38, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "maximum_path_c") < 0)) __PYX_ERR(0, 38, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - } - __pyx_v_paths = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_paths.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_v_values = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_values.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_v_t_ys = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_ys.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_v_t_xs = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_xs.memview)) __PYX_ERR(0, 38, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 38, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_15monotonic_align_4core_maximum_path_c(__pyx_self, __pyx_v_paths, __pyx_v_values, __pyx_v_t_ys, __pyx_v_t_xs); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("maximum_path_c", 0); - __Pyx_XDECREF(__pyx_r); - if (unlikely(!__pyx_v_paths.memview)) { __Pyx_RaiseUnboundLocalError("paths"); __PYX_ERR(0, 38, __pyx_L1_error) } - if (unlikely(!__pyx_v_values.memview)) { __Pyx_RaiseUnboundLocalError("values"); __PYX_ERR(0, 38, __pyx_L1_error) } - if (unlikely(!__pyx_v_t_ys.memview)) { __Pyx_RaiseUnboundLocalError("t_ys"); __PYX_ERR(0, 38, __pyx_L1_error) } - if (unlikely(!__pyx_v_t_xs.memview)) { __Pyx_RaiseUnboundLocalError("t_xs"); __PYX_ERR(0, 38, __pyx_L1_error) } - __pyx_t_1 = __Pyx_void_to_None(__pyx_f_15monotonic_align_4core_maximum_path_c(__pyx_v_paths, __pyx_v_values, __pyx_v_t_ys, __pyx_v_t_xs, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __PYX_XDEC_MEMVIEW(&__pyx_v_paths, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_values, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_t_ys, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_t_xs, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":122 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - -/* Python wrapper */ -static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_shape = 0; - Py_ssize_t __pyx_v_itemsize; - PyObject *__pyx_v_format = 0; - PyObject *__pyx_v_mode = 0; - int __pyx_v_allocate_buffer; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; - PyObject* values[5] = {0,0,0,0,0}; - values[3] = ((PyObject *)__pyx_n_s_c); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(1, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(1, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); - if (value) { values[3] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_allocate_buffer); - if (value) { values[4] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 122, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_shape = ((PyObject*)values[0]); - __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 122, __pyx_L3_error) - __pyx_v_format = values[2]; - __pyx_v_mode = values[3]; - if (values[4]) { - __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 123, __pyx_L3_error) - } else { - - /* "View.MemoryView":123 - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, - * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< - * - * cdef int idx - */ - __pyx_v_allocate_buffer = ((int)1); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 122, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) __PYX_ERR(1, 122, __pyx_L1_error) - if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { - PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(1, 122, __pyx_L1_error) - } - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); - - /* "View.MemoryView":122 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { - int __pyx_v_idx; - Py_ssize_t __pyx_v_i; - Py_ssize_t __pyx_v_dim; - PyObject **__pyx_v_p; - char __pyx_v_order; - int __pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - char *__pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - Py_ssize_t __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - __Pyx_INCREF(__pyx_v_format); - - /* "View.MemoryView":129 - * cdef PyObject **p - * - * self.ndim = len(shape) # <<<<<<<<<<<<<< - * self.itemsize = itemsize - * - */ - if (unlikely(__pyx_v_shape == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 129, __pyx_L1_error) - } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(1, 129, __pyx_L1_error) - __pyx_v_self->ndim = ((int)__pyx_t_1); - - /* "View.MemoryView":130 - * - * self.ndim = len(shape) - * self.itemsize = itemsize # <<<<<<<<<<<<<< - * - * if not self.ndim: - */ - __pyx_v_self->itemsize = __pyx_v_itemsize; - - /* "View.MemoryView":132 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":133 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 133, __pyx_L1_error) - - /* "View.MemoryView":132 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - } - - /* "View.MemoryView":135 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":136 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 136, __pyx_L1_error) - - /* "View.MemoryView":135 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - } - - /* "View.MemoryView":138 - * raise ValueError("itemsize <= 0 for cython.array") - * - * if not isinstance(format, bytes): # <<<<<<<<<<<<<< - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - */ - __pyx_t_2 = PyBytes_Check(__pyx_v_format); - __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":139 - * - * if not isinstance(format, bytes): - * format = format.encode('ASCII') # <<<<<<<<<<<<<< - * self._format = format # keep a reference to the byte string - * self.format = self._format - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - } - } - __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":138 - * raise ValueError("itemsize <= 0 for cython.array") - * - * if not isinstance(format, bytes): # <<<<<<<<<<<<<< - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - */ - } - - /* "View.MemoryView":140 - * if not isinstance(format, bytes): - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< - * self.format = self._format - * - */ - if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(1, 140, __pyx_L1_error) - __pyx_t_3 = __pyx_v_format; - __Pyx_INCREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_format); - __Pyx_DECREF(__pyx_v_self->_format); - __pyx_v_self->_format = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":141 - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - * self.format = self._format # <<<<<<<<<<<<<< - * - * - */ - if (unlikely(__pyx_v_self->_format == Py_None)) { - PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); - __PYX_ERR(1, 141, __pyx_L1_error) - } - __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(1, 141, __pyx_L1_error) - __pyx_v_self->format = __pyx_t_7; - - /* "View.MemoryView":144 - * - * - * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< - * self._strides = self._shape + self.ndim - * - */ - __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); - - /* "View.MemoryView":145 - * - * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) - * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< - * - * if not self._shape: - */ - __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); - - /* "View.MemoryView":147 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":148 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 148, __pyx_L1_error) - - /* "View.MemoryView":147 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - } - - /* "View.MemoryView":151 - * - * - * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - */ - __pyx_t_8 = 0; - __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; - for (;;) { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(1, 151, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 151, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 151, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_dim = __pyx_t_9; - __pyx_v_idx = __pyx_t_8; - __pyx_t_8 = (__pyx_t_8 + 1); - - /* "View.MemoryView":152 - * - * for idx, dim in enumerate(shape): - * if dim <= 0: # <<<<<<<<<<<<<< - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim - */ - __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":153 - * for idx, dim in enumerate(shape): - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< - * self._shape[idx] = dim - * - */ - __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(1, 153, __pyx_L1_error) - - /* "View.MemoryView":152 - * - * for idx, dim in enumerate(shape): - * if dim <= 0: # <<<<<<<<<<<<<< - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim - */ - } - - /* "View.MemoryView":154 - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim # <<<<<<<<<<<<<< - * - * cdef char order - */ - (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; - - /* "View.MemoryView":151 - * - * - * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":157 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 157, __pyx_L1_error) - if (__pyx_t_4) { - - /* "View.MemoryView":158 - * cdef char order - * if mode == 'fortran': - * order = b'F' # <<<<<<<<<<<<<< - * self.mode = u'fortran' - * elif mode == 'c': - */ - __pyx_v_order = 'F'; - - /* "View.MemoryView":159 - * if mode == 'fortran': - * order = b'F' - * self.mode = u'fortran' # <<<<<<<<<<<<<< - * elif mode == 'c': - * order = b'C' - */ - __Pyx_INCREF(__pyx_n_u_fortran); - __Pyx_GIVEREF(__pyx_n_u_fortran); - __Pyx_GOTREF(__pyx_v_self->mode); - __Pyx_DECREF(__pyx_v_self->mode); - __pyx_v_self->mode = __pyx_n_u_fortran; - - /* "View.MemoryView":157 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":160 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 160, __pyx_L1_error) - if (likely(__pyx_t_4)) { - - /* "View.MemoryView":161 - * self.mode = u'fortran' - * elif mode == 'c': - * order = b'C' # <<<<<<<<<<<<<< - * self.mode = u'c' - * else: - */ - __pyx_v_order = 'C'; - - /* "View.MemoryView":162 - * elif mode == 'c': - * order = b'C' - * self.mode = u'c' # <<<<<<<<<<<<<< - * else: - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - */ - __Pyx_INCREF(__pyx_n_u_c); - __Pyx_GIVEREF(__pyx_n_u_c); - __Pyx_GOTREF(__pyx_v_self->mode); - __Pyx_DECREF(__pyx_v_self->mode); - __pyx_v_self->mode = __pyx_n_u_c; - - /* "View.MemoryView":160 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":164 - * self.mode = u'c' - * else: - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< - * - * self.len = fill_contig_strides_array(self._shape, self._strides, - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(1, 164, __pyx_L1_error) - } - __pyx_L10:; - - /* "View.MemoryView":166 - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - * - * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< - * itemsize, self.ndim, order) - * - */ - __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); - - /* "View.MemoryView":169 - * itemsize, self.ndim, order) - * - * self.free_data = allocate_buffer # <<<<<<<<<<<<<< - * self.dtype_is_object = format == b'O' - * if allocate_buffer: - */ - __pyx_v_self->free_data = __pyx_v_allocate_buffer; - - /* "View.MemoryView":170 - * - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< - * if allocate_buffer: - * - */ - __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 170, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 170, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_v_self->dtype_is_object = __pyx_t_4; - - /* "View.MemoryView":171 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_4 = (__pyx_v_allocate_buffer != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":174 - * - * - * self.data = malloc(self.len) # <<<<<<<<<<<<<< - * if not self.data: - * raise MemoryError("unable to allocate array data.") - */ - __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); - - /* "View.MemoryView":175 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":176 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 176, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(1, 176, __pyx_L1_error) - - /* "View.MemoryView":175 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - } - - /* "View.MemoryView":178 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":179 - * - * if self.dtype_is_object: - * p = self.data # <<<<<<<<<<<<<< - * for i in range(self.len / itemsize): - * p[i] = Py_None - */ - __pyx_v_p = ((PyObject **)__pyx_v_self->data); - - /* "View.MemoryView":180 - * if self.dtype_is_object: - * p = self.data - * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< - * p[i] = Py_None - * Py_INCREF(Py_None) - */ - if (unlikely(__pyx_v_itemsize == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(1, 180, __pyx_L1_error) - } - else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { - PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - __PYX_ERR(1, 180, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); - __pyx_t_9 = __pyx_t_1; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_i = __pyx_t_11; - - /* "View.MemoryView":181 - * p = self.data - * for i in range(self.len / itemsize): - * p[i] = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - (__pyx_v_p[__pyx_v_i]) = Py_None; - - /* "View.MemoryView":182 - * for i in range(self.len / itemsize): - * p[i] = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - Py_INCREF(Py_None); - } - - /* "View.MemoryView":178 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - } - - /* "View.MemoryView":171 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":122 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_format); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":185 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * cdef int bufmode = -1 - * if self.mode == u"c": - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_bufmode; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - char *__pyx_t_4; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - Py_ssize_t *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "View.MemoryView":186 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 # <<<<<<<<<<<<<< - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - */ - __pyx_v_bufmode = -1; - - /* "View.MemoryView":187 - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 - * if self.mode == u"c": # <<<<<<<<<<<<<< - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - */ - __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 187, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":188 - * cdef int bufmode = -1 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - */ - __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - - /* "View.MemoryView":187 - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 - * if self.mode == u"c": # <<<<<<<<<<<<<< - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - */ - goto __pyx_L3; - } - - /* "View.MemoryView":189 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": # <<<<<<<<<<<<<< - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - */ - __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 189, __pyx_L1_error) - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":190 - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") - */ - __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - - /* "View.MemoryView":189 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": # <<<<<<<<<<<<<< - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - */ - } - __pyx_L3:; - - /* "View.MemoryView":191 - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): # <<<<<<<<<<<<<< - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - */ - __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":192 - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< - * info.buf = self.data - * info.len = self.len - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 192, __pyx_L1_error) - - /* "View.MemoryView":191 - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): # <<<<<<<<<<<<<< - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - */ - } - - /* "View.MemoryView":193 - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data # <<<<<<<<<<<<<< - * info.len = self.len - * info.ndim = self.ndim - */ - __pyx_t_4 = __pyx_v_self->data; - __pyx_v_info->buf = __pyx_t_4; - - /* "View.MemoryView":194 - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - * info.len = self.len # <<<<<<<<<<<<<< - * info.ndim = self.ndim - * info.shape = self._shape - */ - __pyx_t_5 = __pyx_v_self->len; - __pyx_v_info->len = __pyx_t_5; - - /* "View.MemoryView":195 - * info.buf = self.data - * info.len = self.len - * info.ndim = self.ndim # <<<<<<<<<<<<<< - * info.shape = self._shape - * info.strides = self._strides - */ - __pyx_t_6 = __pyx_v_self->ndim; - __pyx_v_info->ndim = __pyx_t_6; - - /* "View.MemoryView":196 - * info.len = self.len - * info.ndim = self.ndim - * info.shape = self._shape # <<<<<<<<<<<<<< - * info.strides = self._strides - * info.suboffsets = NULL - */ - __pyx_t_7 = __pyx_v_self->_shape; - __pyx_v_info->shape = __pyx_t_7; - - /* "View.MemoryView":197 - * info.ndim = self.ndim - * info.shape = self._shape - * info.strides = self._strides # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = self.itemsize - */ - __pyx_t_7 = __pyx_v_self->_strides; - __pyx_v_info->strides = __pyx_t_7; - - /* "View.MemoryView":198 - * info.shape = self._shape - * info.strides = self._strides - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = self.itemsize - * info.readonly = 0 - */ - __pyx_v_info->suboffsets = NULL; - - /* "View.MemoryView":199 - * info.strides = self._strides - * info.suboffsets = NULL - * info.itemsize = self.itemsize # <<<<<<<<<<<<<< - * info.readonly = 0 - * - */ - __pyx_t_5 = __pyx_v_self->itemsize; - __pyx_v_info->itemsize = __pyx_t_5; - - /* "View.MemoryView":200 - * info.suboffsets = NULL - * info.itemsize = self.itemsize - * info.readonly = 0 # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - __pyx_v_info->readonly = 0; - - /* "View.MemoryView":202 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":203 - * - * if flags & PyBUF_FORMAT: - * info.format = self.format # <<<<<<<<<<<<<< - * else: - * info.format = NULL - */ - __pyx_t_4 = __pyx_v_self->format; - __pyx_v_info->format = __pyx_t_4; - - /* "View.MemoryView":202 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":205 - * info.format = self.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.obj = self - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L5:; - - /* "View.MemoryView":207 - * info.format = NULL - * - * info.obj = self # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "View.MemoryView":185 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * cdef int bufmode = -1 - * if self.mode == u"c": - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":211 - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - * - * def __dealloc__(array self): # <<<<<<<<<<<<<< - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - */ - -/* Python wrapper */ -static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":212 - * - * def __dealloc__(array self): - * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< - * self.callback_free_data(self.data) - * elif self.free_data: - */ - __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":213 - * def __dealloc__(array self): - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) # <<<<<<<<<<<<<< - * elif self.free_data: - * if self.dtype_is_object: - */ - __pyx_v_self->callback_free_data(__pyx_v_self->data); - - /* "View.MemoryView":212 - * - * def __dealloc__(array self): - * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< - * self.callback_free_data(self.data) - * elif self.free_data: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":214 - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - * elif self.free_data: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, - */ - __pyx_t_1 = (__pyx_v_self->free_data != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":215 - * self.callback_free_data(self.data) - * elif self.free_data: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - */ - __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":216 - * elif self.free_data: - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< - * self._strides, self.ndim, False) - * free(self.data) - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); - - /* "View.MemoryView":215 - * self.callback_free_data(self.data) - * elif self.free_data: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - */ - } - - /* "View.MemoryView":218 - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - * free(self.data) # <<<<<<<<<<<<<< - * PyObject_Free(self._shape) - * - */ - free(__pyx_v_self->data); - - /* "View.MemoryView":214 - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - * elif self.free_data: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, - */ - } - __pyx_L3:; - - /* "View.MemoryView":219 - * self._strides, self.ndim, False) - * free(self.data) - * PyObject_Free(self._shape) # <<<<<<<<<<<<<< - * - * @property - */ - PyObject_Free(__pyx_v_self->_shape); - - /* "View.MemoryView":211 - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - * - * def __dealloc__(array self): # <<<<<<<<<<<<<< - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":222 - * - * @property - * def memview(self): # <<<<<<<<<<<<<< - * return self.get_memview() - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":223 - * @property - * def memview(self): - * return self.get_memview() # <<<<<<<<<<<<<< - * - * @cname('get_memview') - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 223, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":222 - * - * @property - * def memview(self): # <<<<<<<<<<<<<< - * return self.get_memview() - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":226 - * - * @cname('get_memview') - * cdef get_memview(self): # <<<<<<<<<<<<<< - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) - */ - -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self) { - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_memview", 0); - - /* "View.MemoryView":227 - * @cname('get_memview') - * cdef get_memview(self): - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< - * return memoryview(self, flags, self.dtype_is_object) - * - */ - __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); - - /* "View.MemoryView":228 - * cdef get_memview(self): - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":226 - * - * @cname('get_memview') - * cdef get_memview(self): # <<<<<<<<<<<<<< - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":230 - * return memoryview(self, flags, self.dtype_is_object) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._shape[0] - * - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__", 0); - - /* "View.MemoryView":231 - * - * def __len__(self): - * return self._shape[0] # <<<<<<<<<<<<<< - * - * def __getattr__(self, attr): - */ - __pyx_r = (__pyx_v_self->_shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":230 - * return memoryview(self, flags, self.dtype_is_object) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._shape[0] - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":233 - * return self._shape[0] - * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getattr__", 0); - - /* "View.MemoryView":234 - * - * def __getattr__(self, attr): - * return getattr(self.memview, attr) # <<<<<<<<<<<<<< - * - * def __getitem__(self, item): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 234, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 234, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":233 - * return self._shape[0] - * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":236 - * return getattr(self.memview, attr) - * - * def __getitem__(self, item): # <<<<<<<<<<<<<< - * return self.memview[item] - * - */ - -/* Python wrapper */ -static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ -static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":237 - * - * def __getitem__(self, item): - * return self.memview[item] # <<<<<<<<<<<<<< - * - * def __setitem__(self, item, value): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":236 - * return getattr(self.memview, attr) - * - * def __getitem__(self, item): # <<<<<<<<<<<<<< - * return self.memview[item] - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":239 - * return self.memview[item] - * - * def __setitem__(self, item, value): # <<<<<<<<<<<<<< - * self.memview[item] = value - * - */ - -/* Python wrapper */ -static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - - /* "View.MemoryView":240 - * - * def __setitem__(self, item, value): - * self.memview[item] = value # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(1, 240, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":239 - * return self.memview[item] - * - * def __setitem__(self, item, value): # <<<<<<<<<<<<<< - * self.memview[item] = value - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":244 - * - * @cname("__pyx_array_new") - * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< - * char *mode, char *buf): - * cdef array result - */ - -static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { - struct __pyx_array_obj *__pyx_v_result = 0; - struct __pyx_array_obj *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("array_cwrapper", 0); - - /* "View.MemoryView":248 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":249 - * - * if buf == NULL: - * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), - */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":248 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":251 - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< - * allocate_buffer=False) - * result.data = buf - */ - /*else*/ { - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_3 = 0; - - /* "View.MemoryView":252 - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), - * allocate_buffer=False) # <<<<<<<<<<<<<< - * result.data = buf - * - */ - __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(1, 252, __pyx_L1_error) - - /* "View.MemoryView":251 - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< - * allocate_buffer=False) - * result.data = buf - */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "View.MemoryView":253 - * result = array(shape, itemsize, format, mode.decode('ASCII'), - * allocate_buffer=False) - * result.data = buf # <<<<<<<<<<<<<< - * - * return result - */ - __pyx_v_result->data = __pyx_v_buf; - } - __pyx_L3:; - - /* "View.MemoryView":255 - * result.data = buf - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":244 - * - * @cname("__pyx_array_new") - * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< - * char *mode, char *buf): - * cdef array result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":281 - * cdef class Enum(object): - * cdef object name - * def __init__(self, name): # <<<<<<<<<<<<<< - * self.name = name - * def __repr__(self): - */ - -/* Python wrapper */ -static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_name = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(1, 281, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_name = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 281, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__", 0); - - /* "View.MemoryView":282 - * cdef object name - * def __init__(self, name): - * self.name = name # <<<<<<<<<<<<<< - * def __repr__(self): - * return self.name - */ - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - __Pyx_GOTREF(__pyx_v_self->name); - __Pyx_DECREF(__pyx_v_self->name); - __pyx_v_self->name = __pyx_v_name; - - /* "View.MemoryView":281 - * cdef class Enum(object): - * cdef object name - * def __init__(self, name): # <<<<<<<<<<<<<< - * self.name = name - * def __repr__(self): - */ - - /* function exit code */ - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":283 - * def __init__(self, name): - * self.name = name - * def __repr__(self): # <<<<<<<<<<<<<< - * return self.name - * - */ - -/* Python wrapper */ -static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":284 - * self.name = name - * def __repr__(self): - * return self.name # <<<<<<<<<<<<<< - * - * cdef generic = Enum("") - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->name); - __pyx_r = __pyx_v_self->name; - goto __pyx_L0; - - /* "View.MemoryView":283 - * def __init__(self, name): - * self.name = name - * def __repr__(self): # <<<<<<<<<<<<<< - * return self.name - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { - PyObject *__pyx_v_state = 0; - PyObject *__pyx_v__dict = 0; - int __pyx_v_use_setstate; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":5 - * cdef object _dict - * cdef bint use_setstate - * state = (self.name,) # <<<<<<<<<<<<<< - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->name); - __Pyx_GIVEREF(__pyx_v_self->name); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); - __pyx_v_state = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "(tree fragment)":6 - * cdef bint use_setstate - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< - * if _dict is not None: - * state += (_dict,) - */ - __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__dict = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":7 - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - __pyx_t_2 = (__pyx_v__dict != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":8 - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - * state += (_dict,) # <<<<<<<<<<<<<< - * use_setstate = True - * else: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v__dict); - __Pyx_GIVEREF(__pyx_v__dict); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); - __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "(tree fragment)":9 - * if _dict is not None: - * state += (_dict,) - * use_setstate = True # <<<<<<<<<<<<<< - * else: - * use_setstate = self.name is not None - */ - __pyx_v_use_setstate = 1; - - /* "(tree fragment)":7 - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - goto __pyx_L3; - } - - /* "(tree fragment)":11 - * use_setstate = True - * else: - * use_setstate = self.name is not None # <<<<<<<<<<<<<< - * if use_setstate: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_self->name != Py_None); - __pyx_v_use_setstate = __pyx_t_3; - } - __pyx_L3:; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - */ - __pyx_t_3 = (__pyx_v_use_setstate != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":13 - * use_setstate = self.name is not None - * if use_setstate: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_184977713); - __Pyx_GIVEREF(__pyx_int_184977713); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - */ - } - - /* "(tree fragment)":15 - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_184977713); - __Pyx_GIVEREF(__pyx_int_184977713); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __pyx_t_5 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - } - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_state); - __Pyx_XDECREF(__pyx_v__dict); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":16 - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":17 - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 17, __pyx_L1_error) - __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":16 - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":298 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory - */ - -static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { - Py_intptr_t __pyx_v_aligned_p; - size_t __pyx_v_offset; - void *__pyx_r; - int __pyx_t_1; - - /* "View.MemoryView":300 - * cdef void *align_pointer(void *memory, size_t alignment) nogil: - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< - * cdef size_t offset - * - */ - __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); - - /* "View.MemoryView":304 - * - * with cython.cdivision(True): - * offset = aligned_p % alignment # <<<<<<<<<<<<<< - * - * if offset > 0: - */ - __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); - - /* "View.MemoryView":306 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - __pyx_t_1 = ((__pyx_v_offset > 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":307 - * - * if offset > 0: - * aligned_p += alignment - offset # <<<<<<<<<<<<<< - * - * return aligned_p - */ - __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); - - /* "View.MemoryView":306 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - } - - /* "View.MemoryView":309 - * aligned_p += alignment - offset - * - * return aligned_p # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = ((void *)__pyx_v_aligned_p); - goto __pyx_L0; - - /* "View.MemoryView":298 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":345 - * cdef __Pyx_TypeInfo *typeinfo - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< - * self.obj = obj - * self.flags = flags - */ - -/* Python wrapper */ -static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_obj = 0; - int __pyx_v_flags; - int __pyx_v_dtype_is_object; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(1, 345, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dtype_is_object); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 345, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_obj = values[0]; - __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 345, __pyx_L3_error) - if (values[2]) { - __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 345, __pyx_L3_error) - } else { - __pyx_v_dtype_is_object = ((int)0); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 345, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "View.MemoryView":346 - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - * self.obj = obj # <<<<<<<<<<<<<< - * self.flags = flags - * if type(self) is memoryview or obj is not None: - */ - __Pyx_INCREF(__pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - __Pyx_GOTREF(__pyx_v_self->obj); - __Pyx_DECREF(__pyx_v_self->obj); - __pyx_v_self->obj = __pyx_v_obj; - - /* "View.MemoryView":347 - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - * self.obj = obj - * self.flags = flags # <<<<<<<<<<<<<< - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - */ - __pyx_v_self->flags = __pyx_v_flags; - - /* "View.MemoryView":348 - * self.obj = obj - * self.flags = flags - * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - */ - __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); - __pyx_t_3 = (__pyx_t_2 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_1 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = (__pyx_v_obj != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (__pyx_t_1) { - - /* "View.MemoryView":349 - * self.flags = flags - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - */ - __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 349, __pyx_L1_error) - - /* "View.MemoryView":350 - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) - */ - __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":351 - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; - - /* "View.MemoryView":352 - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * global __pyx_memoryview_thread_locks_used - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":350 - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) - */ - } - - /* "View.MemoryView":348 - * self.obj = obj - * self.flags = flags - * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - */ - } - - /* "View.MemoryView":355 - * - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - */ - __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":356 - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: - */ - __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - - /* "View.MemoryView":357 - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - */ - __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); - - /* "View.MemoryView":355 - * - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - */ - } - - /* "View.MemoryView":358 - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: # <<<<<<<<<<<<<< - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - */ - __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":359 - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< - * if self.lock is NULL: - * raise MemoryError - */ - __pyx_v_self->lock = PyThread_allocate_lock(); - - /* "View.MemoryView":360 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":361 - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - PyErr_NoMemory(); __PYX_ERR(1, 361, __pyx_L1_error) - - /* "View.MemoryView":360 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - } - - /* "View.MemoryView":358 - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: # <<<<<<<<<<<<<< - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - */ - } - - /* "View.MemoryView":363 - * raise MemoryError - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":364 - * - * if flags & PyBUF_FORMAT: - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< - * else: - * self.dtype_is_object = dtype_is_object - */ - __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L11_bool_binop_done:; - __pyx_v_self->dtype_is_object = __pyx_t_1; - - /* "View.MemoryView":363 - * raise MemoryError - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - */ - goto __pyx_L10; - } - - /* "View.MemoryView":366 - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< - * - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - */ - /*else*/ { - __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; - } - __pyx_L10:; - - /* "View.MemoryView":368 - * self.dtype_is_object = dtype_is_object - * - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< - * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - * self.typeinfo = NULL - */ - __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); - - /* "View.MemoryView":370 - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - * self.typeinfo = NULL # <<<<<<<<<<<<<< - * - * def __dealloc__(memoryview self): - */ - __pyx_v_self->typeinfo = NULL; - - /* "View.MemoryView":345 - * cdef __Pyx_TypeInfo *typeinfo - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< - * self.obj = obj - * self.flags = flags - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":372 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - -/* Python wrapper */ -static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { - int __pyx_v_i; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyThread_type_lock __pyx_t_6; - PyThread_type_lock __pyx_t_7; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":373 - * - * def __dealloc__(memoryview self): - * if self.obj is not None: # <<<<<<<<<<<<<< - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - */ - __pyx_t_1 = (__pyx_v_self->obj != Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":374 - * def __dealloc__(memoryview self): - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - * - */ - __Pyx_ReleaseBuffer((&__pyx_v_self->view)); - - /* "View.MemoryView":373 - * - * def __dealloc__(memoryview self): - * if self.obj is not None: # <<<<<<<<<<<<<< - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":375 - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< - * - * (<__pyx_buffer *> &self.view).obj = NULL - */ - __pyx_t_2 = ((((Py_buffer *)(&__pyx_v_self->view))->obj == Py_None) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":377 - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - * - * (<__pyx_buffer *> &self.view).obj = NULL # <<<<<<<<<<<<<< - * Py_DECREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_self->view))->obj = NULL; - - /* "View.MemoryView":378 - * - * (<__pyx_buffer *> &self.view).obj = NULL - * Py_DECREF(Py_None) # <<<<<<<<<<<<<< - * - * cdef int i - */ - Py_DECREF(Py_None); - - /* "View.MemoryView":375 - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< - * - * (<__pyx_buffer *> &self.view).obj = NULL - */ - } - __pyx_L3:; - - /* "View.MemoryView":382 - * cdef int i - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: # <<<<<<<<<<<<<< - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - */ - __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":383 - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - */ - __pyx_t_3 = __pyx_memoryview_thread_locks_used; - __pyx_t_4 = __pyx_t_3; - for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { - __pyx_v_i = __pyx_t_5; - - /* "View.MemoryView":384 - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - */ - __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":385 - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - */ - __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); - - /* "View.MemoryView":386 - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - */ - __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":388 - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< - * break - * else: - */ - __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); - - /* "View.MemoryView":387 - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - * break - */ - (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; - (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; - - /* "View.MemoryView":386 - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - */ - } - - /* "View.MemoryView":389 - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - * break # <<<<<<<<<<<<<< - * else: - * PyThread_free_lock(self.lock) - */ - goto __pyx_L6_break; - - /* "View.MemoryView":384 - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - */ - } - } - /*else*/ { - - /* "View.MemoryView":391 - * break - * else: - * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: - */ - PyThread_free_lock(__pyx_v_self->lock); - } - __pyx_L6_break:; - - /* "View.MemoryView":382 - * cdef int i - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: # <<<<<<<<<<<<<< - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - */ - } - - /* "View.MemoryView":372 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":393 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf - */ - -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - Py_ssize_t __pyx_v_dim; - char *__pyx_v_itemp; - PyObject *__pyx_v_idx = NULL; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t __pyx_t_3; - PyObject *(*__pyx_t_4)(PyObject *); - PyObject *__pyx_t_5 = NULL; - Py_ssize_t __pyx_t_6; - char *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_item_pointer", 0); - - /* "View.MemoryView":395 - * cdef char *get_item_pointer(memoryview self, object index) except NULL: - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< - * - * for dim, idx in enumerate(index): - */ - __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); - - /* "View.MemoryView":397 - * cdef char *itemp = self.view.buf - * - * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - */ - __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { - __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - } else { - __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 397, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 397, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_4)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 397, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } else { - if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 397, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } - } else { - __pyx_t_5 = __pyx_t_4(__pyx_t_2); - if (unlikely(!__pyx_t_5)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 397, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_5); - } - __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); - __pyx_t_5 = 0; - __pyx_v_dim = __pyx_t_1; - __pyx_t_1 = (__pyx_t_1 + 1); - - /* "View.MemoryView":398 - * - * for dim, idx in enumerate(index): - * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< - * - * return itemp - */ - __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 398, __pyx_L1_error) - __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(1, 398, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_7; - - /* "View.MemoryView":397 - * cdef char *itemp = self.view.buf - * - * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":400 - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - * return itemp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_itemp; - goto __pyx_L0; - - /* "View.MemoryView":393 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":403 - * - * - * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< - * if index is Ellipsis: - * return self - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ -static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - PyObject *__pyx_v_have_slices = NULL; - PyObject *__pyx_v_indices = NULL; - char *__pyx_v_itemp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - char *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":404 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":405 - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: - * return self # <<<<<<<<<<<<<< - * - * have_slices, indices = _unellipsify(index, self.view.ndim) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - goto __pyx_L0; - - /* "View.MemoryView":404 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - } - - /* "View.MemoryView":407 - * return self - * - * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< - * - * cdef char *itemp - */ - __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (likely(__pyx_t_3 != Py_None)) { - PyObject* sequence = __pyx_t_3; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 407, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 407, __pyx_L1_error) - } - __pyx_v_have_slices = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_v_indices = __pyx_t_5; - __pyx_t_5 = 0; - - /* "View.MemoryView":410 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 410, __pyx_L1_error) - if (__pyx_t_2) { - - /* "View.MemoryView":411 - * cdef char *itemp - * if have_slices: - * return memview_slice(self, indices) # <<<<<<<<<<<<<< - * else: - * itemp = self.get_item_pointer(indices) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 411, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":410 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - } - - /* "View.MemoryView":413 - * return memview_slice(self, indices) - * else: - * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< - * return self.convert_item_to_object(itemp) - * - */ - /*else*/ { - __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == ((char *)NULL))) __PYX_ERR(1, 413, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_6; - - /* "View.MemoryView":414 - * else: - * itemp = self.get_item_pointer(indices) - * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< - * - * def __setitem__(memoryview self, object index, object value): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 414, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":403 - * - * - * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< - * if index is Ellipsis: - * return self - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_have_slices); - __Pyx_XDECREF(__pyx_v_indices); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":416 - * return self.convert_item_to_object(itemp) - * - * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") - */ - -/* Python wrapper */ -static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - PyObject *__pyx_v_have_slices = NULL; - PyObject *__pyx_v_obj = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - __Pyx_INCREF(__pyx_v_index); - - /* "View.MemoryView":417 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - __pyx_t_1 = (__pyx_v_self->view.readonly != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":418 - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< - * - * have_slices, index = _unellipsify(index, self.view.ndim) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 418, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(1, 418, __pyx_L1_error) - - /* "View.MemoryView":417 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - } - - /* "View.MemoryView":420 - * raise TypeError("Cannot assign to read-only memoryview") - * - * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< - * - * if have_slices: - */ - __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (likely(__pyx_t_2 != Py_None)) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 420, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 420, __pyx_L1_error) - } - __pyx_v_have_slices = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":422 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 422, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":423 - * - * if have_slices: - * obj = self.is_slice(value) # <<<<<<<<<<<<<< - * if obj: - * self.setitem_slice_assignment(self[index], obj) - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 423, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_obj = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":424 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 424, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":425 - * obj = self.is_slice(value) - * if obj: - * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< - * else: - * self.setitem_slice_assign_scalar(self[index], value) - */ - __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 425, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 425, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "View.MemoryView":424 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":427 - * self.setitem_slice_assignment(self[index], obj) - * else: - * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< - * else: - * self.setitem_indexed(index, value) - */ - /*else*/ { - __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 427, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(1, 427, __pyx_L1_error) - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 427, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L5:; - - /* "View.MemoryView":422 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":429 - * self.setitem_slice_assign_scalar(self[index], value) - * else: - * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< - * - * cdef is_slice(self, obj): - */ - /*else*/ { - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 429, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L4:; - - /* "View.MemoryView":416 - * return self.convert_item_to_object(itemp) - * - * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_have_slices); - __Pyx_XDECREF(__pyx_v_obj); - __Pyx_XDECREF(__pyx_v_index); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":431 - * self.setitem_indexed(index, value) - * - * cdef is_slice(self, obj): # <<<<<<<<<<<<<< - * if not isinstance(obj, memoryview): - * try: - */ - -static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_slice", 0); - __Pyx_INCREF(__pyx_v_obj); - - /* "View.MemoryView":432 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":433 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - /*try:*/ { - - /* "View.MemoryView":434 - * if not isinstance(obj, memoryview): - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< - * self.dtype_is_object) - * except TypeError: - */ - __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":435 - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) # <<<<<<<<<<<<<< - * except TypeError: - * return None - */ - __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 435, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "View.MemoryView":434 - * if not isinstance(obj, memoryview): - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< - * self.dtype_is_object) - * except TypeError: - */ - __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); - __pyx_t_7 = 0; - - /* "View.MemoryView":433 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - } - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L9_try_end; - __pyx_L4_error:; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "View.MemoryView":436 - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - * except TypeError: # <<<<<<<<<<<<<< - * return None - * - */ - __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_9) { - __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(1, 436, __pyx_L6_except_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":437 - * self.dtype_is_object) - * except TypeError: - * return None # <<<<<<<<<<<<<< - * - * return obj - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - goto __pyx_L7_except_return; - } - goto __pyx_L6_except_error; - __pyx_L6_except_error:; - - /* "View.MemoryView":433 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); - goto __pyx_L1_error; - __pyx_L7_except_return:; - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); - goto __pyx_L0; - __pyx_L9_try_end:; - } - - /* "View.MemoryView":432 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - } - - /* "View.MemoryView":439 - * return None - * - * return obj # <<<<<<<<<<<<<< - * - * cdef setitem_slice_assignment(self, dst, src): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_obj); - __pyx_r = __pyx_v_obj; - goto __pyx_L0; - - /* "View.MemoryView":431 - * self.setitem_indexed(index, value) - * - * cdef is_slice(self, obj): # <<<<<<<<<<<<<< - * if not isinstance(obj, memoryview): - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_obj); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":441 - * return obj - * - * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice dst_slice - * cdef __Pyx_memviewslice src_slice - */ - -static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { - __Pyx_memviewslice __pyx_v_dst_slice; - __Pyx_memviewslice __pyx_v_src_slice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - __Pyx_memviewslice *__pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); - - /* "View.MemoryView":445 - * cdef __Pyx_memviewslice src_slice - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) - */ - if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(1, 445, __pyx_L1_error) - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 445, __pyx_L1_error) - - /* "View.MemoryView":446 - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< - * src.ndim, dst.ndim, self.dtype_is_object) - * - */ - if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(1, 446, __pyx_L1_error) - __pyx_t_2 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice)); if (unlikely(__pyx_t_2 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 446, __pyx_L1_error) - - /* "View.MemoryView":447 - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":445 - * cdef __Pyx_memviewslice src_slice - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) - */ - __pyx_t_6 = __pyx_memoryview_copy_contents((__pyx_t_1[0]), (__pyx_t_2[0]), __pyx_t_4, __pyx_t_5, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 445, __pyx_L1_error) - - /* "View.MemoryView":441 - * return obj - * - * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice dst_slice - * cdef __Pyx_memviewslice src_slice - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":449 - * src.ndim, dst.ndim, self.dtype_is_object) - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< - * cdef int array[128] - * cdef void *tmp = NULL - */ - -static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { - int __pyx_v_array[0x80]; - void *__pyx_v_tmp; - void *__pyx_v_item; - __Pyx_memviewslice *__pyx_v_dst_slice; - __Pyx_memviewslice __pyx_v_tmp_slice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - char const *__pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); - - /* "View.MemoryView":451 - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): - * cdef int array[128] - * cdef void *tmp = NULL # <<<<<<<<<<<<<< - * cdef void *item - * - */ - __pyx_v_tmp = NULL; - - /* "View.MemoryView":456 - * cdef __Pyx_memviewslice *dst_slice - * cdef __Pyx_memviewslice tmp_slice - * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< - * - * if self.view.itemsize > sizeof(array): - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 456, __pyx_L1_error) - __pyx_v_dst_slice = __pyx_t_1; - - /* "View.MemoryView":458 - * dst_slice = get_slice_from_memview(dst, &tmp_slice) - * - * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - */ - __pyx_t_2 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":459 - * - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< - * if tmp == NULL: - * raise MemoryError - */ - __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); - - /* "View.MemoryView":460 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - __pyx_t_2 = ((__pyx_v_tmp == NULL) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":461 - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * item = tmp - * else: - */ - PyErr_NoMemory(); __PYX_ERR(1, 461, __pyx_L1_error) - - /* "View.MemoryView":460 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - } - - /* "View.MemoryView":462 - * if tmp == NULL: - * raise MemoryError - * item = tmp # <<<<<<<<<<<<<< - * else: - * item = array - */ - __pyx_v_item = __pyx_v_tmp; - - /* "View.MemoryView":458 - * dst_slice = get_slice_from_memview(dst, &tmp_slice) - * - * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":464 - * item = tmp - * else: - * item = array # <<<<<<<<<<<<<< - * - * try: - */ - /*else*/ { - __pyx_v_item = ((void *)__pyx_v_array); - } - __pyx_L3:; - - /* "View.MemoryView":466 - * item = array - * - * try: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * ( item)[0] = value - */ - /*try:*/ { - - /* "View.MemoryView":467 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - __pyx_t_2 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":468 - * try: - * if self.dtype_is_object: - * ( item)[0] = value # <<<<<<<<<<<<<< - * else: - * self.assign_item_from_object( item, value) - */ - (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); - - /* "View.MemoryView":467 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":470 - * ( item)[0] = value - * else: - * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 470, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L8:; - - /* "View.MemoryView":474 - * - * - * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - */ - __pyx_t_2 = ((__pyx_v_self->view.suboffsets != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":475 - * - * if self.view.suboffsets != NULL: - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - * item, self.dtype_is_object) - */ - __pyx_t_3 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 475, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":474 - * - * - * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - */ - } - - /* "View.MemoryView":476 - * if self.view.suboffsets != NULL: - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< - * item, self.dtype_is_object) - * finally: - */ - __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); - } - - /* "View.MemoryView":479 - * item, self.dtype_is_object) - * finally: - * PyMem_Free(tmp) # <<<<<<<<<<<<<< - * - * cdef setitem_indexed(self, index, value): - */ - /*finally:*/ { - /*normal exit:*/{ - PyMem_Free(__pyx_v_tmp); - goto __pyx_L7; - } - __pyx_L6_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_7); - __Pyx_XGOTREF(__pyx_t_8); - __Pyx_XGOTREF(__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_10); - __Pyx_XGOTREF(__pyx_t_11); - __Pyx_XGOTREF(__pyx_t_12); - __pyx_t_4 = __pyx_lineno; __pyx_t_5 = __pyx_clineno; __pyx_t_6 = __pyx_filename; - { - PyMem_Free(__pyx_v_tmp); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_XGIVEREF(__pyx_t_12); - __Pyx_ExceptionReset(__pyx_t_10, __pyx_t_11, __pyx_t_12); - } - __Pyx_XGIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_XGIVEREF(__pyx_t_9); - __Pyx_ErrRestore(__pyx_t_7, __pyx_t_8, __pyx_t_9); - __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; - __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_5; __pyx_filename = __pyx_t_6; - goto __pyx_L1_error; - } - __pyx_L7:; - } - - /* "View.MemoryView":449 - * src.ndim, dst.ndim, self.dtype_is_object) - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< - * cdef int array[128] - * cdef void *tmp = NULL - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":481 - * PyMem_Free(tmp) - * - * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) - */ - -static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - char *__pyx_v_itemp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - char *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_indexed", 0); - - /* "View.MemoryView":482 - * - * cdef setitem_indexed(self, index, value): - * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< - * self.assign_item_from_object(itemp, value) - * - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == ((char *)NULL))) __PYX_ERR(1, 482, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_1; - - /* "View.MemoryView":483 - * cdef setitem_indexed(self, index, value): - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< - * - * cdef convert_item_to_object(self, char *itemp): - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 483, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":481 - * PyMem_Free(tmp) - * - * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":485 - * self.assign_item_from_object(itemp, value) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - -static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { - PyObject *__pyx_v_struct = NULL; - PyObject *__pyx_v_bytesitem = 0; - PyObject *__pyx_v_result = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - size_t __pyx_t_10; - int __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":488 - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - * import struct # <<<<<<<<<<<<<< - * cdef bytes bytesitem - * - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 488, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":491 - * cdef bytes bytesitem - * - * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< - * try: - * result = struct.unpack(self.view.format, bytesitem) - */ - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 491, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "View.MemoryView":493 - * bytesitem = itemp[:self.view.itemsize] - * try: - * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< - * except struct.error: - * raise ValueError("Unable to convert item to object") - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); - __Pyx_INCREF(__pyx_v_bytesitem); - __Pyx_GIVEREF(__pyx_v_bytesitem); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_result = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - } - - /* "View.MemoryView":497 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - /*else:*/ { - __pyx_t_10 = strlen(__pyx_v_self->view.format); - __pyx_t_11 = ((__pyx_t_10 == 1) != 0); - if (__pyx_t_11) { - - /* "View.MemoryView":498 - * else: - * if len(self.view.format) == 1: - * return result[0] # <<<<<<<<<<<<<< - * return result - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 498, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L6_except_return; - - /* "View.MemoryView":497 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - } - - /* "View.MemoryView":499 - * if len(self.view.format) == 1: - * return result[0] - * return result # <<<<<<<<<<<<<< - * - * cdef assign_item_from_object(self, char *itemp, object value): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_result); - __pyx_r = __pyx_v_result; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "View.MemoryView":494 - * try: - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: # <<<<<<<<<<<<<< - * raise ValueError("Unable to convert item to object") - * else: - */ - __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 494, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); - __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; - if (__pyx_t_8) { - __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(1, 494, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_1); - - /* "View.MemoryView":495 - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< - * else: - * if len(self.view.format) == 1: - */ - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 495, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_Raise(__pyx_t_6, 0, 0, 0); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __PYX_ERR(1, 495, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "View.MemoryView":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "View.MemoryView":485 - * self.assign_item_from_object(itemp, value) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_struct); - __Pyx_XDECREF(__pyx_v_bytesitem); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":501 - * return result - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - -static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { - PyObject *__pyx_v_struct = NULL; - char __pyx_v_c; - PyObject *__pyx_v_bytesvalue = 0; - Py_ssize_t __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - Py_ssize_t __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - char *__pyx_t_11; - char *__pyx_t_12; - char *__pyx_t_13; - char *__pyx_t_14; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":504 - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - * import struct # <<<<<<<<<<<<<< - * cdef char c - * cdef bytes bytesvalue - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 504, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":509 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - __pyx_t_2 = PyTuple_Check(__pyx_v_value); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "View.MemoryView":510 - * - * if isinstance(value, tuple): - * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< - * else: - * bytesvalue = struct.pack(self.view.format, value) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 510, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":509 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":512 - * bytesvalue = struct.pack(self.view.format, *value) - * else: - * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< - * - * for i, c in enumerate(bytesvalue): - */ - /*else*/ { - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; - __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; - __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); - __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 512, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":514 - * bytesvalue = struct.pack(self.view.format, value) - * - * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< - * itemp[i] = c - * - */ - __pyx_t_9 = 0; - if (unlikely(__pyx_v_bytesvalue == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); - __PYX_ERR(1, 514, __pyx_L1_error) - } - __Pyx_INCREF(__pyx_v_bytesvalue); - __pyx_t_10 = __pyx_v_bytesvalue; - __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); - __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); - for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { - __pyx_t_11 = __pyx_t_14; - __pyx_v_c = (__pyx_t_11[0]); - - /* "View.MemoryView":515 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - __pyx_v_i = __pyx_t_9; - - /* "View.MemoryView":514 - * bytesvalue = struct.pack(self.view.format, value) - * - * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< - * itemp[i] = c - * - */ - __pyx_t_9 = (__pyx_t_9 + 1); - - /* "View.MemoryView":515 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; - } - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - - /* "View.MemoryView":501 - * return result - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_struct); - __Pyx_XDECREF(__pyx_v_bytesvalue); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":518 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t *__pyx_t_4; - char *__pyx_t_5; - void *__pyx_t_6; - int __pyx_t_7; - Py_ssize_t __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "View.MemoryView":519 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - */ - __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->view.readonly != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":520 - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< - * - * if flags & PyBUF_ND: - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 520, __pyx_L1_error) - - /* "View.MemoryView":519 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - */ - } - - /* "View.MemoryView":522 - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - * if flags & PyBUF_ND: # <<<<<<<<<<<<<< - * info.shape = self.view.shape - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":523 - * - * if flags & PyBUF_ND: - * info.shape = self.view.shape # <<<<<<<<<<<<<< - * else: - * info.shape = NULL - */ - __pyx_t_4 = __pyx_v_self->view.shape; - __pyx_v_info->shape = __pyx_t_4; - - /* "View.MemoryView":522 - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - * if flags & PyBUF_ND: # <<<<<<<<<<<<<< - * info.shape = self.view.shape - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":525 - * info.shape = self.view.shape - * else: - * info.shape = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_STRIDES: - */ - /*else*/ { - __pyx_v_info->shape = NULL; - } - __pyx_L6:; - - /* "View.MemoryView":527 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":528 - * - * if flags & PyBUF_STRIDES: - * info.strides = self.view.strides # <<<<<<<<<<<<<< - * else: - * info.strides = NULL - */ - __pyx_t_4 = __pyx_v_self->view.strides; - __pyx_v_info->strides = __pyx_t_4; - - /* "View.MemoryView":527 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - goto __pyx_L7; - } - - /* "View.MemoryView":530 - * info.strides = self.view.strides - * else: - * info.strides = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_INDIRECT: - */ - /*else*/ { - __pyx_v_info->strides = NULL; - } - __pyx_L7:; - - /* "View.MemoryView":532 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":533 - * - * if flags & PyBUF_INDIRECT: - * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< - * else: - * info.suboffsets = NULL - */ - __pyx_t_4 = __pyx_v_self->view.suboffsets; - __pyx_v_info->suboffsets = __pyx_t_4; - - /* "View.MemoryView":532 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":535 - * info.suboffsets = self.view.suboffsets - * else: - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - /*else*/ { - __pyx_v_info->suboffsets = NULL; - } - __pyx_L8:; - - /* "View.MemoryView":537 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":538 - * - * if flags & PyBUF_FORMAT: - * info.format = self.view.format # <<<<<<<<<<<<<< - * else: - * info.format = NULL - */ - __pyx_t_5 = __pyx_v_self->view.format; - __pyx_v_info->format = __pyx_t_5; - - /* "View.MemoryView":537 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":540 - * info.format = self.view.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.buf = self.view.buf - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L9:; - - /* "View.MemoryView":542 - * info.format = NULL - * - * info.buf = self.view.buf # <<<<<<<<<<<<<< - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize - */ - __pyx_t_6 = __pyx_v_self->view.buf; - __pyx_v_info->buf = __pyx_t_6; - - /* "View.MemoryView":543 - * - * info.buf = self.view.buf - * info.ndim = self.view.ndim # <<<<<<<<<<<<<< - * info.itemsize = self.view.itemsize - * info.len = self.view.len - */ - __pyx_t_7 = __pyx_v_self->view.ndim; - __pyx_v_info->ndim = __pyx_t_7; - - /* "View.MemoryView":544 - * info.buf = self.view.buf - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< - * info.len = self.view.len - * info.readonly = self.view.readonly - */ - __pyx_t_8 = __pyx_v_self->view.itemsize; - __pyx_v_info->itemsize = __pyx_t_8; - - /* "View.MemoryView":545 - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize - * info.len = self.view.len # <<<<<<<<<<<<<< - * info.readonly = self.view.readonly - * info.obj = self - */ - __pyx_t_8 = __pyx_v_self->view.len; - __pyx_v_info->len = __pyx_t_8; - - /* "View.MemoryView":546 - * info.itemsize = self.view.itemsize - * info.len = self.view.len - * info.readonly = self.view.readonly # <<<<<<<<<<<<<< - * info.obj = self - * - */ - __pyx_t_1 = __pyx_v_self->view.readonly; - __pyx_v_info->readonly = __pyx_t_1; - - /* "View.MemoryView":547 - * info.len = self.view.len - * info.readonly = self.view.readonly - * info.obj = self # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "View.MemoryView":518 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":553 - * - * @property - * def T(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":554 - * @property - * def T(self): - * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< - * transpose_memslice(&result.from_slice) - * return result - */ - __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 554, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(1, 554, __pyx_L1_error) - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":555 - * def T(self): - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< - * return result - * - */ - __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 555, __pyx_L1_error) - - /* "View.MemoryView":556 - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - * return result # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":553 - * - * @property - * def T(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":559 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":560 - * @property - * def base(self): - * return self.obj # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->obj); - __pyx_r = __pyx_v_self->obj; - goto __pyx_L0; - - /* "View.MemoryView":559 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":563 - * - * @property - * def shape(self): # <<<<<<<<<<<<<< - * return tuple([length for length in self.view.shape[:self.view.ndim]]) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_length; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":564 - * @property - * def shape(self): - * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); - for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { - __pyx_t_2 = __pyx_t_4; - __pyx_v_length = (__pyx_t_2[0]); - __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":563 - * - * @property - * def shape(self): # <<<<<<<<<<<<<< - * return tuple([length for length in self.view.shape[:self.view.ndim]]) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":567 - * - * @property - * def strides(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_stride; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":568 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":570 - * if self.view.strides == NULL: - * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 570, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(1, 570, __pyx_L1_error) - - /* "View.MemoryView":568 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - } - - /* "View.MemoryView":572 - * raise ValueError("Buffer view does not expose strides") - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); - for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { - __pyx_t_3 = __pyx_t_5; - __pyx_v_stride = (__pyx_t_3[0]); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "View.MemoryView":567 - * - * @property - * def strides(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":575 - * - * @property - * def suboffsets(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - Py_ssize_t *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":576 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":577 - * def suboffsets(self): - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__13, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":576 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - } - - /* "View.MemoryView":579 - * return (-1,) * self.view.ndim - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); - for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { - __pyx_t_4 = __pyx_t_6; - __pyx_v_suboffset = (__pyx_t_4[0]); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":575 - * - * @property - * def suboffsets(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":582 - * - * @property - * def ndim(self): # <<<<<<<<<<<<<< - * return self.view.ndim - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":583 - * @property - * def ndim(self): - * return self.view.ndim # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":582 - * - * @property - * def ndim(self): # <<<<<<<<<<<<<< - * return self.view.ndim - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":586 - * - * @property - * def itemsize(self): # <<<<<<<<<<<<<< - * return self.view.itemsize - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":587 - * @property - * def itemsize(self): - * return self.view.itemsize # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 587, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":586 - * - * @property - * def itemsize(self): # <<<<<<<<<<<<<< - * return self.view.itemsize - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":590 - * - * @property - * def nbytes(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":591 - * @property - * def nbytes(self): - * return self.size * self.view.itemsize # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 591, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 591, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 591, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":590 - * - * @property - * def nbytes(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":594 - * - * @property - * def size(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_v_result = NULL; - PyObject *__pyx_v_length = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":595 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - __pyx_t_1 = (__pyx_v_self->_size == Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":596 - * def size(self): - * if self._size is None: - * result = 1 # <<<<<<<<<<<<<< - * - * for length in self.view.shape[:self.view.ndim]: - */ - __Pyx_INCREF(__pyx_int_1); - __pyx_v_result = __pyx_int_1; - - /* "View.MemoryView":598 - * result = 1 - * - * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< - * result *= length - * - */ - __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); - for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { - __pyx_t_3 = __pyx_t_5; - __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 598, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); - __pyx_t_6 = 0; - - /* "View.MemoryView":599 - * - * for length in self.view.shape[:self.view.ndim]: - * result *= length # <<<<<<<<<<<<<< - * - * self._size = result - */ - __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 599, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); - __pyx_t_6 = 0; - } - - /* "View.MemoryView":601 - * result *= length - * - * self._size = result # <<<<<<<<<<<<<< - * - * return self._size - */ - __Pyx_INCREF(__pyx_v_result); - __Pyx_GIVEREF(__pyx_v_result); - __Pyx_GOTREF(__pyx_v_self->_size); - __Pyx_DECREF(__pyx_v_self->_size); - __pyx_v_self->_size = __pyx_v_result; - - /* "View.MemoryView":595 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - } - - /* "View.MemoryView":603 - * self._size = result - * - * return self._size # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->_size); - __pyx_r = __pyx_v_self->_size; - goto __pyx_L0; - - /* "View.MemoryView":594 - * - * @property - * def size(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_length); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":605 - * return self._size - * - * def __len__(self): # <<<<<<<<<<<<<< - * if self.view.ndim >= 1: - * return self.view.shape[0] - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__len__", 0); - - /* "View.MemoryView":606 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":607 - * def __len__(self): - * if self.view.ndim >= 1: - * return self.view.shape[0] # <<<<<<<<<<<<<< - * - * return 0 - */ - __pyx_r = (__pyx_v_self->view.shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":606 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - } - - /* "View.MemoryView":609 - * return self.view.shape[0] - * - * return 0 # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":605 - * return self._size - * - * def __len__(self): # <<<<<<<<<<<<<< - * if self.view.ndim >= 1: - * return self.view.shape[0] - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":611 - * return 0 - * - * def __repr__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__, - * id(self)) - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":612 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":613 - * def __repr__(self): - * return "" % (self.base.__class__.__name__, - * id(self)) # <<<<<<<<<<<<<< - * - * def __str__(self): - */ - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 613, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "View.MemoryView":612 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":611 - * return 0 - * - * def __repr__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__, - * id(self)) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":615 - * id(self)) - * - * def __str__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__,) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__str__", 0); - - /* "View.MemoryView":616 - * - * def __str__(self): - * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":615 - * id(self)) - * - * def __str__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__,) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":619 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice *__pyx_v_mslice; - __Pyx_memviewslice __pyx_v_tmp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_c_contig", 0); - - /* "View.MemoryView":622 - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 622, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":623 - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< - * - * def is_f_contig(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 623, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":619 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":625 - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - * def is_f_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice *__pyx_v_mslice; - __Pyx_memviewslice __pyx_v_tmp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_f_contig", 0); - - /* "View.MemoryView":628 - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 628, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":629 - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< - * - * def copy(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 629, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":625 - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - * def is_f_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":631 - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - * def copy(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice __pyx_v_mslice; - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy", 0); - - /* "View.MemoryView":633 - * def copy(self): - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< - * - * slice_copy(self, &mslice) - */ - __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); - - /* "View.MemoryView":635 - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - * - * slice_copy(self, &mslice) # <<<<<<<<<<<<<< - * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, - * self.view.itemsize, - */ - __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); - - /* "View.MemoryView":636 - * - * slice_copy(self, &mslice) - * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< - * self.view.itemsize, - * flags|PyBUF_C_CONTIGUOUS, - */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), ((char *)"c"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 636, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":641 - * self.dtype_is_object) - * - * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< - * - * def copy_fortran(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 641, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":631 - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - * def copy(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":643 - * return memoryview_copy_from_slice(self, &mslice) - * - * def copy_fortran(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice __pyx_v_src; - __Pyx_memviewslice __pyx_v_dst; - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy_fortran", 0); - - /* "View.MemoryView":645 - * def copy_fortran(self): - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< - * - * slice_copy(self, &src) - */ - __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); - - /* "View.MemoryView":647 - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - * - * slice_copy(self, &src) # <<<<<<<<<<<<<< - * dst = slice_copy_contig(&src, "fortran", self.view.ndim, - * self.view.itemsize, - */ - __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); - - /* "View.MemoryView":648 - * - * slice_copy(self, &src) - * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< - * self.view.itemsize, - * flags|PyBUF_F_CONTIGUOUS, - */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), ((char *)"fortran"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 648, __pyx_L1_error) - __pyx_v_dst = __pyx_t_1; - - /* "View.MemoryView":653 - * self.dtype_is_object) - * - * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 653, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":643 - * return memoryview_copy_from_slice(self, &mslice) - * - * def copy_fortran(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":657 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - */ - -static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { - struct __pyx_memoryview_obj *__pyx_v_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); - - /* "View.MemoryView":658 - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< - * result.typeinfo = typeinfo - * return result - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_o); - __Pyx_GIVEREF(__pyx_v_o); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":659 - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo # <<<<<<<<<<<<<< - * return result - * - */ - __pyx_v_result->typeinfo = __pyx_v_typeinfo; - - /* "View.MemoryView":660 - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - * return result # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_check') - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":657 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":663 - * - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< - * return isinstance(o, memoryview) - * - */ - -static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("memoryview_check", 0); - - /* "View.MemoryView":664 - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): - * return isinstance(o, memoryview) # <<<<<<<<<<<<<< - * - * cdef tuple _unellipsify(object index, int ndim): - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); - __pyx_r = __pyx_t_1; - goto __pyx_L0; - - /* "View.MemoryView":663 - * - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< - * return isinstance(o, memoryview) - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":666 - * return isinstance(o, memoryview) - * - * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< - * """ - * Replace all ellipses with full slices and fill incomplete indices with - */ - -static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { - PyObject *__pyx_v_tup = NULL; - PyObject *__pyx_v_result = NULL; - int __pyx_v_have_slices; - int __pyx_v_seen_ellipsis; - CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; - PyObject *__pyx_v_item = NULL; - Py_ssize_t __pyx_v_nslices; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - PyObject *(*__pyx_t_6)(PyObject *); - PyObject *__pyx_t_7 = NULL; - Py_ssize_t __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_unellipsify", 0); - - /* "View.MemoryView":671 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - __pyx_t_1 = PyTuple_Check(__pyx_v_index); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":672 - * """ - * if not isinstance(index, tuple): - * tup = (index,) # <<<<<<<<<<<<<< - * else: - * tup = index - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_index); - __Pyx_GIVEREF(__pyx_v_index); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); - __pyx_v_tup = __pyx_t_3; - __pyx_t_3 = 0; - - /* "View.MemoryView":671 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":674 - * tup = (index,) - * else: - * tup = index # <<<<<<<<<<<<<< - * - * result = [] - */ - /*else*/ { - __Pyx_INCREF(__pyx_v_index); - __pyx_v_tup = __pyx_v_index; - } - __pyx_L3:; - - /* "View.MemoryView":676 - * tup = index - * - * result = [] # <<<<<<<<<<<<<< - * have_slices = False - * seen_ellipsis = False - */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 676, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_result = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":677 - * - * result = [] - * have_slices = False # <<<<<<<<<<<<<< - * seen_ellipsis = False - * for idx, item in enumerate(tup): - */ - __pyx_v_have_slices = 0; - - /* "View.MemoryView":678 - * result = [] - * have_slices = False - * seen_ellipsis = False # <<<<<<<<<<<<<< - * for idx, item in enumerate(tup): - * if item is Ellipsis: - */ - __pyx_v_seen_ellipsis = 0; - - /* "View.MemoryView":679 - * have_slices = False - * seen_ellipsis = False - * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< - * if item is Ellipsis: - * if not seen_ellipsis: - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_3 = __pyx_int_0; - if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { - __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - } else { - __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 679, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_6)) { - if (likely(PyList_CheckExact(__pyx_t_4))) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 679, __pyx_L1_error) - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - } else { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 679, __pyx_L1_error) - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - } - } else { - __pyx_t_7 = __pyx_t_6(__pyx_t_4); - if (unlikely(!__pyx_t_7)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 679, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_7); - } - __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); - __pyx_t_7 = 0; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); - __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); - __pyx_t_3 = __pyx_t_7; - __pyx_t_7 = 0; - - /* "View.MemoryView":680 - * seen_ellipsis = False - * for idx, item in enumerate(tup): - * if item is Ellipsis: # <<<<<<<<<<<<<< - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - */ - __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":681 - * for idx, item in enumerate(tup): - * if item is Ellipsis: - * if not seen_ellipsis: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True - */ - __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":682 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(1, 682, __pyx_L1_error) - __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__16); - __Pyx_GIVEREF(__pyx_slice__16); - PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__16); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "View.MemoryView":683 - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True # <<<<<<<<<<<<<< - * else: - * result.append(slice(None)) - */ - __pyx_v_seen_ellipsis = 1; - - /* "View.MemoryView":681 - * for idx, item in enumerate(tup): - * if item is Ellipsis: - * if not seen_ellipsis: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True - */ - goto __pyx_L7; - } - - /* "View.MemoryView":685 - * seen_ellipsis = True - * else: - * result.append(slice(None)) # <<<<<<<<<<<<<< - * have_slices = True - * else: - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__16); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 685, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":686 - * else: - * result.append(slice(None)) - * have_slices = True # <<<<<<<<<<<<<< - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): - */ - __pyx_v_have_slices = 1; - - /* "View.MemoryView":680 - * seen_ellipsis = False - * for idx, item in enumerate(tup): - * if item is Ellipsis: # <<<<<<<<<<<<<< - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - */ - goto __pyx_L6; - } - - /* "View.MemoryView":688 - * have_slices = True - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - */ - /*else*/ { - __pyx_t_2 = PySlice_Check(__pyx_v_item); - __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_10) { - } else { - __pyx_t_1 = __pyx_t_10; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); - __pyx_t_1 = __pyx_t_10; - __pyx_L9_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":689 - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): - * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< - * - * have_slices = have_slices or isinstance(item, slice) - */ - __pyx_t_7 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 689, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 689, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_11, 0, 0, 0); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __PYX_ERR(1, 689, __pyx_L1_error) - - /* "View.MemoryView":688 - * have_slices = True - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - */ - } - - /* "View.MemoryView":691 - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< - * result.append(item) - * - */ - __pyx_t_10 = (__pyx_v_have_slices != 0); - if (!__pyx_t_10) { - } else { - __pyx_t_1 = __pyx_t_10; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_10 = PySlice_Check(__pyx_v_item); - __pyx_t_2 = (__pyx_t_10 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L11_bool_binop_done:; - __pyx_v_have_slices = __pyx_t_1; - - /* "View.MemoryView":692 - * - * have_slices = have_slices or isinstance(item, slice) - * result.append(item) # <<<<<<<<<<<<<< - * - * nslices = ndim - len(result) - */ - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 692, __pyx_L1_error) - } - __pyx_L6:; - - /* "View.MemoryView":679 - * have_slices = False - * seen_ellipsis = False - * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< - * if item is Ellipsis: - * if not seen_ellipsis: - */ - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":694 - * result.append(item) - * - * nslices = ndim - len(result) # <<<<<<<<<<<<<< - * if nslices: - * result.extend([slice(None)] * nslices) - */ - __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(1, 694, __pyx_L1_error) - __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); - - /* "View.MemoryView":695 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - __pyx_t_1 = (__pyx_v_nslices != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":696 - * nslices = ndim - len(result) - * if nslices: - * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< - * - * return have_slices or nslices, tuple(result) - */ - __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 696, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__16); - __Pyx_GIVEREF(__pyx_slice__16); - PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__16); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 696, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":695 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - } - - /* "View.MemoryView":698 - * result.extend([slice(None)] * nslices) - * - * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - */ - __Pyx_XDECREF(__pyx_r); - if (!__pyx_v_have_slices) { - } else { - __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L14_bool_binop_done; - } - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_L14_bool_binop_done:; - __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = ((PyObject*)__pyx_t_11); - __pyx_t_11 = 0; - goto __pyx_L0; - - /* "View.MemoryView":666 - * return isinstance(o, memoryview) - * - * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< - * """ - * Replace all ellipses with full slices and fill incomplete indices with - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_tup); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_XDECREF(__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":700 - * return have_slices or nslices, tuple(result) - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - */ - -static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t *__pyx_t_1; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); - - /* "View.MemoryView":701 - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") - */ - __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); - for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { - __pyx_t_1 = __pyx_t_3; - __pyx_v_suboffset = (__pyx_t_1[0]); - - /* "View.MemoryView":702 - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * raise ValueError("Indirect dimensions not supported") - * - */ - __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":703 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 703, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __PYX_ERR(1, 703, __pyx_L1_error) - - /* "View.MemoryView":702 - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * raise ValueError("Indirect dimensions not supported") - * - */ - } - } - - /* "View.MemoryView":700 - * return have_slices or nslices, tuple(result) - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":710 - * - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< - * cdef int new_ndim = 0, suboffset_dim = -1, dim - * cdef bint negative_step - */ - -static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { - int __pyx_v_new_ndim; - int __pyx_v_suboffset_dim; - int __pyx_v_dim; - __Pyx_memviewslice __pyx_v_src; - __Pyx_memviewslice __pyx_v_dst; - __Pyx_memviewslice *__pyx_v_p_src; - struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; - __Pyx_memviewslice *__pyx_v_p_dst; - int *__pyx_v_p_suboffset_dim; - Py_ssize_t __pyx_v_start; - Py_ssize_t __pyx_v_stop; - Py_ssize_t __pyx_v_step; - int __pyx_v_have_start; - int __pyx_v_have_stop; - int __pyx_v_have_step; - PyObject *__pyx_v_index = NULL; - struct __pyx_memoryview_obj *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - struct __pyx_memoryview_obj *__pyx_t_4; - char *__pyx_t_5; - int __pyx_t_6; - Py_ssize_t __pyx_t_7; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - Py_ssize_t __pyx_t_10; - int __pyx_t_11; - Py_ssize_t __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memview_slice", 0); - - /* "View.MemoryView":711 - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): - * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< - * cdef bint negative_step - * cdef __Pyx_memviewslice src, dst - */ - __pyx_v_new_ndim = 0; - __pyx_v_suboffset_dim = -1; - - /* "View.MemoryView":718 - * - * - * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< - * - * cdef _memoryviewslice memviewsliceobj - */ - (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); - - /* "View.MemoryView":722 - * cdef _memoryviewslice memviewsliceobj - * - * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< - * - * if isinstance(memview, _memoryviewslice): - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(1, 722, __pyx_L1_error) - } - } - #endif - - /* "View.MemoryView":724 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":725 - * - * if isinstance(memview, _memoryviewslice): - * memviewsliceobj = memview # <<<<<<<<<<<<<< - * p_src = &memviewsliceobj.from_slice - * else: - */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 725, __pyx_L1_error) - __pyx_t_3 = ((PyObject *)__pyx_v_memview); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":726 - * if isinstance(memview, _memoryviewslice): - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< - * else: - * slice_copy(memview, &src) - */ - __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); - - /* "View.MemoryView":724 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - goto __pyx_L3; - } - - /* "View.MemoryView":728 - * p_src = &memviewsliceobj.from_slice - * else: - * slice_copy(memview, &src) # <<<<<<<<<<<<<< - * p_src = &src - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); - - /* "View.MemoryView":729 - * else: - * slice_copy(memview, &src) - * p_src = &src # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_p_src = (&__pyx_v_src); - } - __pyx_L3:; - - /* "View.MemoryView":735 - * - * - * dst.memview = p_src.memview # <<<<<<<<<<<<<< - * dst.data = p_src.data - * - */ - __pyx_t_4 = __pyx_v_p_src->memview; - __pyx_v_dst.memview = __pyx_t_4; - - /* "View.MemoryView":736 - * - * dst.memview = p_src.memview - * dst.data = p_src.data # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __pyx_v_p_src->data; - __pyx_v_dst.data = __pyx_t_5; - - /* "View.MemoryView":741 - * - * - * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< - * cdef int *p_suboffset_dim = &suboffset_dim - * cdef Py_ssize_t start, stop, step - */ - __pyx_v_p_dst = (&__pyx_v_dst); - - /* "View.MemoryView":742 - * - * cdef __Pyx_memviewslice *p_dst = &dst - * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< - * cdef Py_ssize_t start, stop, step - * cdef bint have_start, have_stop, have_step - */ - __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); - - /* "View.MemoryView":746 - * cdef bint have_start, have_stop, have_step - * - * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< - * if PyIndex_Check(index): - * slice_memviewslice( - */ - __pyx_t_6 = 0; - if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { - __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - } else { - __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 746, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 746, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_8)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 746, __pyx_L1_error) - #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - } else { - if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 746, __pyx_L1_error) - #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - } - } else { - __pyx_t_9 = __pyx_t_8(__pyx_t_3); - if (unlikely(!__pyx_t_9)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 746, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_9); - } - __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); - __pyx_t_9 = 0; - __pyx_v_dim = __pyx_t_6; - __pyx_t_6 = (__pyx_t_6 + 1); - - /* "View.MemoryView":747 - * - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): # <<<<<<<<<<<<<< - * slice_memviewslice( - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - */ - __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":751 - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< - * 0, 0, 0, # have_{start,stop,step} - * False) - */ - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 751, __pyx_L1_error) - - /* "View.MemoryView":748 - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): - * slice_memviewslice( # <<<<<<<<<<<<<< - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 748, __pyx_L1_error) - - /* "View.MemoryView":747 - * - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): # <<<<<<<<<<<<<< - * slice_memviewslice( - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - */ - goto __pyx_L6; - } - - /* "View.MemoryView":754 - * 0, 0, 0, # have_{start,stop,step} - * False) - * elif index is None: # <<<<<<<<<<<<<< - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - */ - __pyx_t_2 = (__pyx_v_index == Py_None); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":755 - * False) - * elif index is None: - * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 - */ - (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; - - /* "View.MemoryView":756 - * elif index is None: - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< - * p_dst.suboffsets[new_ndim] = -1 - * new_ndim += 1 - */ - (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; - - /* "View.MemoryView":757 - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< - * new_ndim += 1 - * else: - */ - (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; - - /* "View.MemoryView":758 - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 - * new_ndim += 1 # <<<<<<<<<<<<<< - * else: - * start = index.start or 0 - */ - __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - - /* "View.MemoryView":754 - * 0, 0, 0, # have_{start,stop,step} - * False) - * elif index is None: # <<<<<<<<<<<<<< - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - */ - goto __pyx_L6; - } - - /* "View.MemoryView":760 - * new_ndim += 1 - * else: - * start = index.start or 0 # <<<<<<<<<<<<<< - * stop = index.stop or 0 - * step = index.step or 0 - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 760, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 760, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 760, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L7_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L7_bool_binop_done:; - __pyx_v_start = __pyx_t_10; - - /* "View.MemoryView":761 - * else: - * start = index.start or 0 - * stop = index.stop or 0 # <<<<<<<<<<<<<< - * step = index.step or 0 - * - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 761, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 761, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 761, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L9_bool_binop_done:; - __pyx_v_stop = __pyx_t_10; - - /* "View.MemoryView":762 - * start = index.start or 0 - * stop = index.stop or 0 - * step = index.step or 0 # <<<<<<<<<<<<<< - * - * have_start = index.start is not None - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 762, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 762, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 762, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L11_bool_binop_done:; - __pyx_v_step = __pyx_t_10; - - /* "View.MemoryView":764 - * step = index.step or 0 - * - * have_start = index.start is not None # <<<<<<<<<<<<<< - * have_stop = index.stop is not None - * have_step = index.step is not None - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 764, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_start = __pyx_t_1; - - /* "View.MemoryView":765 - * - * have_start = index.start is not None - * have_stop = index.stop is not None # <<<<<<<<<<<<<< - * have_step = index.step is not None - * - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 765, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_stop = __pyx_t_1; - - /* "View.MemoryView":766 - * have_start = index.start is not None - * have_stop = index.stop is not None - * have_step = index.step is not None # <<<<<<<<<<<<<< - * - * slice_memviewslice( - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 766, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_step = __pyx_t_1; - - /* "View.MemoryView":768 - * have_step = index.step is not None - * - * slice_memviewslice( # <<<<<<<<<<<<<< - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 768, __pyx_L1_error) - - /* "View.MemoryView":774 - * have_start, have_stop, have_step, - * True) - * new_ndim += 1 # <<<<<<<<<<<<<< - * - * if isinstance(memview, _memoryviewslice): - */ - __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - } - __pyx_L6:; - - /* "View.MemoryView":746 - * cdef bint have_start, have_stop, have_step - * - * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< - * if PyIndex_Check(index): - * slice_memviewslice( - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":776 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":777 - * - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, - */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - - /* "View.MemoryView":778 - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< - * memviewsliceobj.to_dtype_func, - * memview.dtype_is_object) - */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 778, __pyx_L1_error) } - - /* "View.MemoryView":779 - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * else: - */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 779, __pyx_L1_error) } - - /* "View.MemoryView":777 - * - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 777, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 777, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":776 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - } - - /* "View.MemoryView":782 - * memview.dtype_is_object) - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * - */ - /*else*/ { - __Pyx_XDECREF(((PyObject *)__pyx_r)); - - /* "View.MemoryView":783 - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, - * memview.dtype_is_object) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "View.MemoryView":782 - * memview.dtype_is_object) - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * - */ - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 782, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":710 - * - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< - * cdef int new_ndim = 0, suboffset_dim = -1, dim - * cdef bint negative_step - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); - __Pyx_XDECREF(__pyx_v_index); - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":807 - * - * @cname('__pyx_memoryview_slice_memviewslice') - * cdef int slice_memviewslice( # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - */ - -static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { - Py_ssize_t __pyx_v_new_shape; - int __pyx_v_negative_step; - int __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":827 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":829 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - __pyx_t_1 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":830 - * - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if not 0 <= start < shape: - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":829 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - } - - /* "View.MemoryView":831 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - __pyx_t_1 = (0 <= __pyx_v_start); - if (__pyx_t_1) { - __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); - } - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":832 - * start += shape - * if not 0 <= start < shape: - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< - * else: - * - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 832, __pyx_L1_error) - - /* "View.MemoryView":831 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - } - - /* "View.MemoryView":827 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":835 - * else: - * - * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< - * - * if have_step and step == 0: - */ - /*else*/ { - __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); - if (__pyx_t_1) { - } else { - __pyx_t_2 = __pyx_t_1; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_1 = ((__pyx_v_step < 0) != 0); - __pyx_t_2 = __pyx_t_1; - __pyx_L6_bool_binop_done:; - __pyx_v_negative_step = __pyx_t_2; - - /* "View.MemoryView":837 - * negative_step = have_step != 0 and step < 0 - * - * if have_step and step == 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - * - */ - __pyx_t_1 = (__pyx_v_have_step != 0); - if (__pyx_t_1) { - } else { - __pyx_t_2 = __pyx_t_1; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_1 = ((__pyx_v_step == 0) != 0); - __pyx_t_2 = __pyx_t_1; - __pyx_L9_bool_binop_done:; - if (__pyx_t_2) { - - /* "View.MemoryView":838 - * - * if have_step and step == 0: - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 838, __pyx_L1_error) - - /* "View.MemoryView":837 - * negative_step = have_step != 0 and step < 0 - * - * if have_step and step == 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - * - */ - } - - /* "View.MemoryView":841 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - __pyx_t_2 = (__pyx_v_have_start != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":842 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - __pyx_t_2 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":843 - * if have_start: - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if start < 0: - * start = 0 - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":844 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - __pyx_t_2 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":845 - * start += shape - * if start < 0: - * start = 0 # <<<<<<<<<<<<<< - * elif start >= shape: - * if negative_step: - */ - __pyx_v_start = 0; - - /* "View.MemoryView":844 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - } - - /* "View.MemoryView":842 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - goto __pyx_L12; - } - - /* "View.MemoryView":846 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":847 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":848 - * elif start >= shape: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = shape - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":847 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L14; - } - - /* "View.MemoryView":850 - * start = shape - 1 - * else: - * start = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - /*else*/ { - __pyx_v_start = __pyx_v_shape; - } - __pyx_L14:; - - /* "View.MemoryView":846 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - } - __pyx_L12:; - - /* "View.MemoryView":841 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - goto __pyx_L11; - } - - /* "View.MemoryView":852 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":853 - * else: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = 0 - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":852 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L15; - } - - /* "View.MemoryView":855 - * start = shape - 1 - * else: - * start = 0 # <<<<<<<<<<<<<< - * - * if have_stop: - */ - /*else*/ { - __pyx_v_start = 0; - } - __pyx_L15:; - } - __pyx_L11:; - - /* "View.MemoryView":857 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - __pyx_t_2 = (__pyx_v_have_stop != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":858 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - __pyx_t_2 = ((__pyx_v_stop < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":859 - * if have_stop: - * if stop < 0: - * stop += shape # <<<<<<<<<<<<<< - * if stop < 0: - * stop = 0 - */ - __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); - - /* "View.MemoryView":860 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - __pyx_t_2 = ((__pyx_v_stop < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":861 - * stop += shape - * if stop < 0: - * stop = 0 # <<<<<<<<<<<<<< - * elif stop > shape: - * stop = shape - */ - __pyx_v_stop = 0; - - /* "View.MemoryView":860 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - } - - /* "View.MemoryView":858 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - goto __pyx_L17; - } - - /* "View.MemoryView":862 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":863 - * stop = 0 - * elif stop > shape: - * stop = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - __pyx_v_stop = __pyx_v_shape; - - /* "View.MemoryView":862 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - } - __pyx_L17:; - - /* "View.MemoryView":857 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - goto __pyx_L16; - } - - /* "View.MemoryView":865 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":866 - * else: - * if negative_step: - * stop = -1 # <<<<<<<<<<<<<< - * else: - * stop = shape - */ - __pyx_v_stop = -1L; - - /* "View.MemoryView":865 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - goto __pyx_L19; - } - - /* "View.MemoryView":868 - * stop = -1 - * else: - * stop = shape # <<<<<<<<<<<<<< - * - * if not have_step: - */ - /*else*/ { - __pyx_v_stop = __pyx_v_shape; - } - __pyx_L19:; - } - __pyx_L16:; - - /* "View.MemoryView":870 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":871 - * - * if not have_step: - * step = 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_step = 1; - - /* "View.MemoryView":870 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - } - - /* "View.MemoryView":875 - * - * with cython.cdivision(True): - * new_shape = (stop - start) // step # <<<<<<<<<<<<<< - * - * if (stop - start) - step * new_shape: - */ - __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); - - /* "View.MemoryView":877 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":878 - * - * if (stop - start) - step * new_shape: - * new_shape += 1 # <<<<<<<<<<<<<< - * - * if new_shape < 0: - */ - __pyx_v_new_shape = (__pyx_v_new_shape + 1); - - /* "View.MemoryView":877 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - } - - /* "View.MemoryView":880 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":881 - * - * if new_shape < 0: - * new_shape = 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_new_shape = 0; - - /* "View.MemoryView":880 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - } - - /* "View.MemoryView":884 - * - * - * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< - * dst.shape[new_ndim] = new_shape - * dst.suboffsets[new_ndim] = suboffset - */ - (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); - - /* "View.MemoryView":885 - * - * dst.strides[new_ndim] = stride * step - * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< - * dst.suboffsets[new_ndim] = suboffset - * - */ - (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; - - /* "View.MemoryView":886 - * dst.strides[new_ndim] = stride * step - * dst.shape[new_ndim] = new_shape - * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; - } - __pyx_L3:; - - /* "View.MemoryView":889 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":890 - * - * if suboffset_dim[0] < 0: - * dst.data += start * stride # <<<<<<<<<<<<<< - * else: - * dst.suboffsets[suboffset_dim[0]] += start * stride - */ - __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); - - /* "View.MemoryView":889 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - goto __pyx_L23; - } - - /* "View.MemoryView":892 - * dst.data += start * stride - * else: - * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< - * - * if suboffset >= 0: - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_suboffset_dim[0]); - (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); - } - __pyx_L23:; - - /* "View.MemoryView":894 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":895 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":896 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":897 - * if not is_slice: - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " - */ - __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); - - /* "View.MemoryView":896 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - goto __pyx_L26; - } - - /* "View.MemoryView":899 - * dst.data = ( dst.data)[0] + suboffset - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< - * "must be indexed and not sliced", dim) - * else: - */ - /*else*/ { - - /* "View.MemoryView":900 - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " - * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< - * else: - * suboffset_dim[0] = new_ndim - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 899, __pyx_L1_error) - } - __pyx_L26:; - - /* "View.MemoryView":895 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - goto __pyx_L25; - } - - /* "View.MemoryView":902 - * "must be indexed and not sliced", dim) - * else: - * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< - * - * return 0 - */ - /*else*/ { - (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; - } - __pyx_L25:; - - /* "View.MemoryView":894 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - } - - /* "View.MemoryView":904 - * suboffset_dim[0] = new_ndim - * - * return 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":807 - * - * @cname('__pyx_memoryview_slice_memviewslice') - * cdef int slice_memviewslice( # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = -1; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":910 - * - * @cname('__pyx_pybuffer_index') - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - */ - -static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { - Py_ssize_t __pyx_v_shape; - Py_ssize_t __pyx_v_stride; - Py_ssize_t __pyx_v_suboffset; - Py_ssize_t __pyx_v_itemsize; - char *__pyx_v_resultp; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("pybuffer_index", 0); - - /* "View.MemoryView":912 - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< - * cdef Py_ssize_t itemsize = view.itemsize - * cdef char *resultp - */ - __pyx_v_suboffset = -1L; - - /* "View.MemoryView":913 - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< - * cdef char *resultp - * - */ - __pyx_t_1 = __pyx_v_view->itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":916 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":917 - * - * if view.ndim == 0: - * shape = view.len / itemsize # <<<<<<<<<<<<<< - * stride = itemsize - * else: - */ - if (unlikely(__pyx_v_itemsize == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(1, 917, __pyx_L1_error) - } - else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { - PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - __PYX_ERR(1, 917, __pyx_L1_error) - } - __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); - - /* "View.MemoryView":918 - * if view.ndim == 0: - * shape = view.len / itemsize - * stride = itemsize # <<<<<<<<<<<<<< - * else: - * shape = view.shape[dim] - */ - __pyx_v_stride = __pyx_v_itemsize; - - /* "View.MemoryView":916 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - goto __pyx_L3; - } - - /* "View.MemoryView":920 - * stride = itemsize - * else: - * shape = view.shape[dim] # <<<<<<<<<<<<<< - * stride = view.strides[dim] - * if view.suboffsets != NULL: - */ - /*else*/ { - __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); - - /* "View.MemoryView":921 - * else: - * shape = view.shape[dim] - * stride = view.strides[dim] # <<<<<<<<<<<<<< - * if view.suboffsets != NULL: - * suboffset = view.suboffsets[dim] - */ - __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); - - /* "View.MemoryView":922 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":923 - * stride = view.strides[dim] - * if view.suboffsets != NULL: - * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< - * - * if index < 0: - */ - __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); - - /* "View.MemoryView":922 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - } - } - __pyx_L3:; - - /* "View.MemoryView":925 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - __pyx_t_2 = ((__pyx_v_index < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":926 - * - * if index < 0: - * index += view.shape[dim] # <<<<<<<<<<<<<< - * if index < 0: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - */ - __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); - - /* "View.MemoryView":927 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - __pyx_t_2 = ((__pyx_v_index < 0) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":928 - * index += view.shape[dim] - * if index < 0: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< - * - * if index >= shape: - */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 928, __pyx_L1_error) - - /* "View.MemoryView":927 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":925 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - } - - /* "View.MemoryView":930 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * if index >= shape: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":931 - * - * if index >= shape: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< - * - * resultp = bufp + index * stride - */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 931, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 931, __pyx_L1_error) - - /* "View.MemoryView":930 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * if index >= shape: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":933 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * resultp = bufp + index * stride # <<<<<<<<<<<<<< - * if suboffset >= 0: - * resultp = ( resultp)[0] + suboffset - */ - __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); - - /* "View.MemoryView":934 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":935 - * resultp = bufp + index * stride - * if suboffset >= 0: - * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< - * - * return resultp - */ - __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); - - /* "View.MemoryView":934 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - } - - /* "View.MemoryView":937 - * resultp = ( resultp)[0] + suboffset - * - * return resultp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_resultp; - goto __pyx_L0; - - /* "View.MemoryView":910 - * - * @cname('__pyx_pybuffer_index') - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":943 - * - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< - * cdef int ndim = memslice.memview.view.ndim - * - */ - -static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { - int __pyx_v_ndim; - Py_ssize_t *__pyx_v_shape; - Py_ssize_t *__pyx_v_strides; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_r; - int __pyx_t_1; - Py_ssize_t *__pyx_t_2; - long __pyx_t_3; - long __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":944 - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: - * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< - * - * cdef Py_ssize_t *shape = memslice.shape - */ - __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; - __pyx_v_ndim = __pyx_t_1; - - /* "View.MemoryView":946 - * cdef int ndim = memslice.memview.view.ndim - * - * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< - * cdef Py_ssize_t *strides = memslice.strides - * - */ - __pyx_t_2 = __pyx_v_memslice->shape; - __pyx_v_shape = __pyx_t_2; - - /* "View.MemoryView":947 - * - * cdef Py_ssize_t *shape = memslice.shape - * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __pyx_v_memslice->strides; - __pyx_v_strides = __pyx_t_2; - - /* "View.MemoryView":951 - * - * cdef int i, j - * for i in range(ndim / 2): # <<<<<<<<<<<<<< - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] - */ - __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); - __pyx_t_4 = __pyx_t_3; - for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":952 - * cdef int i, j - * for i in range(ndim / 2): - * j = ndim - 1 - i # <<<<<<<<<<<<<< - * strides[i], strides[j] = strides[j], strides[i] - * shape[i], shape[j] = shape[j], shape[i] - */ - __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); - - /* "View.MemoryView":953 - * for i in range(ndim / 2): - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< - * shape[i], shape[j] = shape[j], shape[i] - * - */ - __pyx_t_5 = (__pyx_v_strides[__pyx_v_j]); - __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); - (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; - (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; - - /* "View.MemoryView":954 - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] - * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - */ - __pyx_t_6 = (__pyx_v_shape[__pyx_v_j]); - __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); - (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; - (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; - - /* "View.MemoryView":956 - * shape[i], shape[j] = shape[j], shape[i] - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - */ - __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); - if (!__pyx_t_8) { - } else { - __pyx_t_7 = __pyx_t_8; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); - __pyx_t_7 = __pyx_t_8; - __pyx_L6_bool_binop_done:; - if (__pyx_t_7) { - - /* "View.MemoryView":957 - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< - * - * return 1 - */ - __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 957, __pyx_L1_error) - - /* "View.MemoryView":956 - * shape[i], shape[j] = shape[j], shape[i] - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - */ - } - } - - /* "View.MemoryView":959 - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - * return 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 1; - goto __pyx_L0; - - /* "View.MemoryView":943 - * - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< - * cdef int ndim = memslice.memview.view.ndim - * - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = 0; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":976 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - */ - -/* Python wrapper */ -static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":977 - * - * def __dealloc__(self): - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< - * - * cdef convert_item_to_object(self, char *itemp): - */ - __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); - - /* "View.MemoryView":976 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":979 - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) - */ - -static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":980 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":981 - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) # <<<<<<<<<<<<<< - * else: - * return memoryview.convert_item_to_object(self, itemp) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 981, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":980 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - } - - /* "View.MemoryView":983 - * return self.to_object_func(itemp) - * else: - * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< - * - * cdef assign_item_from_object(self, char *itemp, object value): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":979 - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":985 - * return memoryview.convert_item_to_object(self, itemp) - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) - */ - -static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":986 - * - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< - * self.to_dtype_func(itemp, value) - * else: - */ - __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":987 - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< - * else: - * memoryview.assign_item_from_object(self, itemp, value) - */ - __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 987, __pyx_L1_error) - - /* "View.MemoryView":986 - * - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< - * self.to_dtype_func(itemp, value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":989 - * self.to_dtype_func(itemp, value) - * else: - * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< - * - * @property - */ - /*else*/ { - __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 989, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":985 - * return memoryview.convert_item_to_object(self, itemp) - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":992 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.from_object - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":993 - * @property - * def base(self): - * return self.from_object # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->from_object); - __pyx_r = __pyx_v_self->from_object; - goto __pyx_L0; - - /* "View.MemoryView":992 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.from_object - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":999 - * - * @cname('__pyx_memoryview_fromslice') - * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< - * int ndim, - * object (*to_object_func)(char *), - */ - -static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { - struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_v_length = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - __Pyx_TypeInfo *__pyx_t_4; - Py_buffer __pyx_t_5; - Py_ssize_t *__pyx_t_6; - Py_ssize_t *__pyx_t_7; - Py_ssize_t *__pyx_t_8; - Py_ssize_t __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_fromslice", 0); - - /* "View.MemoryView":1007 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1008 - * - * if memviewslice.memview == Py_None: - * return None # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "View.MemoryView":1007 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - } - - /* "View.MemoryView":1013 - * - * - * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< - * - * result.from_slice = memviewslice - */ - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); - __Pyx_INCREF(__pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1015 - * result = _memoryviewslice(None, 0, dtype_is_object) - * - * result.from_slice = memviewslice # <<<<<<<<<<<<<< - * __PYX_INC_MEMVIEW(&memviewslice, 1) - * - */ - __pyx_v_result->from_slice = __pyx_v_memviewslice; - - /* "View.MemoryView":1016 - * - * result.from_slice = memviewslice - * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< - * - * result.from_object = ( memviewslice.memview).base - */ - __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); - - /* "View.MemoryView":1018 - * __PYX_INC_MEMVIEW(&memviewslice, 1) - * - * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< - * result.typeinfo = memviewslice.memview.typeinfo - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1018, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_result->from_object); - __Pyx_DECREF(__pyx_v_result->from_object); - __pyx_v_result->from_object = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":1019 - * - * result.from_object = ( memviewslice.memview).base - * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< - * - * result.view = memviewslice.memview.view - */ - __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; - __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; - - /* "View.MemoryView":1021 - * result.typeinfo = memviewslice.memview.typeinfo - * - * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< - * result.view.buf = memviewslice.data - * result.view.ndim = ndim - */ - __pyx_t_5 = __pyx_v_memviewslice.memview->view; - __pyx_v_result->__pyx_base.view = __pyx_t_5; - - /* "View.MemoryView":1022 - * - * result.view = memviewslice.memview.view - * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None - */ - __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); - - /* "View.MemoryView":1023 - * result.view = memviewslice.memview.view - * result.view.buf = memviewslice.data - * result.view.ndim = ndim # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &result.view).obj = Py_None - * Py_INCREF(Py_None) - */ - __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; - - /* "View.MemoryView":1024 - * result.view.buf = memviewslice.data - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; - - /* "View.MemoryView":1025 - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":1027 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1028 - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: - * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< - * else: - * result.flags = PyBUF_RECORDS_RO - */ - __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; - - /* "View.MemoryView":1027 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1030 - * result.flags = PyBUF_RECORDS - * else: - * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< - * - * result.view.shape = result.from_slice.shape - */ - /*else*/ { - __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; - } - __pyx_L4:; - - /* "View.MemoryView":1032 - * result.flags = PyBUF_RECORDS_RO - * - * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< - * result.view.strides = result.from_slice.strides - * - */ - __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); - - /* "View.MemoryView":1033 - * - * result.view.shape = result.from_slice.shape - * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); - - /* "View.MemoryView":1036 - * - * - * result.view.suboffsets = NULL # <<<<<<<<<<<<<< - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: - */ - __pyx_v_result->__pyx_base.view.suboffsets = NULL; - - /* "View.MemoryView":1037 - * - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - */ - __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); - for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { - __pyx_t_6 = __pyx_t_8; - __pyx_v_suboffset = (__pyx_t_6[0]); - - /* "View.MemoryView":1038 - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets - * break - */ - __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1039 - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); - - /* "View.MemoryView":1040 - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - * break # <<<<<<<<<<<<<< - * - * result.view.len = result.view.itemsize - */ - goto __pyx_L6_break; - - /* "View.MemoryView":1038 - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets - * break - */ - } - } - __pyx_L6_break:; - - /* "View.MemoryView":1042 - * break - * - * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< - * for length in result.view.shape[:ndim]: - * result.view.len *= length - */ - __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - - /* "View.MemoryView":1043 - * - * result.view.len = result.view.itemsize - * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< - * result.view.len *= length - * - */ - __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); - for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { - __pyx_t_6 = __pyx_t_8; - __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1044 - * result.view.len = result.view.itemsize - * for length in result.view.shape[:ndim]: - * result.view.len *= length # <<<<<<<<<<<<<< - * - * result.to_object_func = to_object_func - */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - } - - /* "View.MemoryView":1046 - * result.view.len *= length - * - * result.to_object_func = to_object_func # <<<<<<<<<<<<<< - * result.to_dtype_func = to_dtype_func - * - */ - __pyx_v_result->to_object_func = __pyx_v_to_object_func; - - /* "View.MemoryView":1047 - * - * result.to_object_func = to_object_func - * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< - * - * return result - */ - __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; - - /* "View.MemoryView":1049 - * result.to_dtype_func = to_dtype_func - * - * return result # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":999 - * - * @cname('__pyx_memoryview_fromslice') - * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< - * int ndim, - * object (*to_object_func)(char *), - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XDECREF(__pyx_v_length); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1052 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - */ - -static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { - struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; - __Pyx_memviewslice *__pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_slice_from_memview", 0); - - /* "View.MemoryView":1055 - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1056 - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): - * obj = memview # <<<<<<<<<<<<<< - * return &obj.from_slice - * else: - */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 1056, __pyx_L1_error) - __pyx_t_3 = ((PyObject *)__pyx_v_memview); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":1057 - * if isinstance(memview, _memoryviewslice): - * obj = memview - * return &obj.from_slice # <<<<<<<<<<<<<< - * else: - * slice_copy(memview, mslice) - */ - __pyx_r = (&__pyx_v_obj->from_slice); - goto __pyx_L0; - - /* "View.MemoryView":1055 - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - } - - /* "View.MemoryView":1059 - * return &obj.from_slice - * else: - * slice_copy(memview, mslice) # <<<<<<<<<<<<<< - * return mslice - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); - - /* "View.MemoryView":1060 - * else: - * slice_copy(memview, mslice) - * return mslice # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_slice_copy') - */ - __pyx_r = __pyx_v_mslice; - goto __pyx_L0; - } - - /* "View.MemoryView":1052 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_obj); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1063 - * - * @cname('__pyx_memoryview_slice_copy') - * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< - * cdef int dim - * cdef (Py_ssize_t*) shape, strides, suboffsets - */ - -static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { - int __pyx_v_dim; - Py_ssize_t *__pyx_v_shape; - Py_ssize_t *__pyx_v_strides; - Py_ssize_t *__pyx_v_suboffsets; - __Pyx_RefNannyDeclarations - Py_ssize_t *__pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - Py_ssize_t __pyx_t_5; - __Pyx_RefNannySetupContext("slice_copy", 0); - - /* "View.MemoryView":1067 - * cdef (Py_ssize_t*) shape, strides, suboffsets - * - * shape = memview.view.shape # <<<<<<<<<<<<<< - * strides = memview.view.strides - * suboffsets = memview.view.suboffsets - */ - __pyx_t_1 = __pyx_v_memview->view.shape; - __pyx_v_shape = __pyx_t_1; - - /* "View.MemoryView":1068 - * - * shape = memview.view.shape - * strides = memview.view.strides # <<<<<<<<<<<<<< - * suboffsets = memview.view.suboffsets - * - */ - __pyx_t_1 = __pyx_v_memview->view.strides; - __pyx_v_strides = __pyx_t_1; - - /* "View.MemoryView":1069 - * shape = memview.view.shape - * strides = memview.view.strides - * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< - * - * dst.memview = <__pyx_memoryview *> memview - */ - __pyx_t_1 = __pyx_v_memview->view.suboffsets; - __pyx_v_suboffsets = __pyx_t_1; - - /* "View.MemoryView":1071 - * suboffsets = memview.view.suboffsets - * - * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< - * dst.data = memview.view.buf - * - */ - __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); - - /* "View.MemoryView":1072 - * - * dst.memview = <__pyx_memoryview *> memview - * dst.data = memview.view.buf # <<<<<<<<<<<<<< - * - * for dim in range(memview.view.ndim): - */ - __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); - - /* "View.MemoryView":1074 - * dst.data = memview.view.buf - * - * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] - */ - __pyx_t_2 = __pyx_v_memview->view.ndim; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_dim = __pyx_t_4; - - /* "View.MemoryView":1075 - * - * for dim in range(memview.view.ndim): - * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< - * dst.strides[dim] = strides[dim] - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - */ - (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); - - /* "View.MemoryView":1076 - * for dim in range(memview.view.ndim): - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - * - */ - (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); - - /* "View.MemoryView":1077 - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_object') - */ - if ((__pyx_v_suboffsets != 0)) { - __pyx_t_5 = (__pyx_v_suboffsets[__pyx_v_dim]); - } else { - __pyx_t_5 = -1L; - } - (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; - } - - /* "View.MemoryView":1063 - * - * @cname('__pyx_memoryview_slice_copy') - * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< - * cdef int dim - * cdef (Py_ssize_t*) shape, strides, suboffsets - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":1080 - * - * @cname('__pyx_memoryview_copy_object') - * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - */ - -static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { - __Pyx_memviewslice __pyx_v_memviewslice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_copy", 0); - - /* "View.MemoryView":1083 - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< - * return memoryview_copy_from_slice(memview, &memviewslice) - * - */ - __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); - - /* "View.MemoryView":1084 - * cdef __Pyx_memviewslice memviewslice - * slice_copy(memview, &memviewslice) - * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_object_from_slice') - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1084, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1080 - * - * @cname('__pyx_memoryview_copy_object') - * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1087 - * - * @cname('__pyx_memoryview_copy_object_from_slice') - * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< - * """ - * Create a new memoryview object from a given memoryview object and slice. - */ - -static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { - PyObject *(*__pyx_v_to_object_func)(char *); - int (*__pyx_v_to_dtype_func)(char *, PyObject *); - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *(*__pyx_t_3)(char *); - int (*__pyx_t_4)(char *, PyObject *); - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); - - /* "View.MemoryView":1094 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1095 - * - * if isinstance(memview, _memoryviewslice): - * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - * else: - */ - __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; - __pyx_v_to_object_func = __pyx_t_3; - - /* "View.MemoryView":1096 - * if isinstance(memview, _memoryviewslice): - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< - * else: - * to_object_func = NULL - */ - __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; - __pyx_v_to_dtype_func = __pyx_t_4; - - /* "View.MemoryView":1094 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1098 - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - * else: - * to_object_func = NULL # <<<<<<<<<<<<<< - * to_dtype_func = NULL - * - */ - /*else*/ { - __pyx_v_to_object_func = NULL; - - /* "View.MemoryView":1099 - * else: - * to_object_func = NULL - * to_dtype_func = NULL # <<<<<<<<<<<<<< - * - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, - */ - __pyx_v_to_dtype_func = NULL; - } - __pyx_L3:; - - /* "View.MemoryView":1101 - * to_dtype_func = NULL - * - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< - * to_object_func, to_dtype_func, - * memview.dtype_is_object) - */ - __Pyx_XDECREF(__pyx_r); - - /* "View.MemoryView":1103 - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, - * to_object_func, to_dtype_func, - * memview.dtype_is_object) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 1101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1087 - * - * @cname('__pyx_memoryview_copy_object_from_slice') - * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< - * """ - * Create a new memoryview object from a given memoryview object and slice. - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1109 - * - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< - * if arg < 0: - * return -arg - */ - -static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { - Py_ssize_t __pyx_r; - int __pyx_t_1; - - /* "View.MemoryView":1110 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - __pyx_t_1 = ((__pyx_v_arg < 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1111 - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: - * return -arg # <<<<<<<<<<<<<< - * else: - * return arg - */ - __pyx_r = (-__pyx_v_arg); - goto __pyx_L0; - - /* "View.MemoryView":1110 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - } - - /* "View.MemoryView":1113 - * return -arg - * else: - * return arg # <<<<<<<<<<<<<< - * - * @cname('__pyx_get_best_slice_order') - */ - /*else*/ { - __pyx_r = __pyx_v_arg; - goto __pyx_L0; - } - - /* "View.MemoryView":1109 - * - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< - * if arg < 0: - * return -arg - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1116 - * - * @cname('__pyx_get_best_slice_order') - * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< - * """ - * Figure out the best memory access order for a given slice. - */ - -static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { - int __pyx_v_i; - Py_ssize_t __pyx_v_c_stride; - Py_ssize_t __pyx_v_f_stride; - char __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1121 - * """ - * cdef int i - * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< - * cdef Py_ssize_t f_stride = 0 - * - */ - __pyx_v_c_stride = 0; - - /* "View.MemoryView":1122 - * cdef int i - * cdef Py_ssize_t c_stride = 0 - * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< - * - * for i in range(ndim - 1, -1, -1): - */ - __pyx_v_f_stride = 0; - - /* "View.MemoryView":1124 - * cdef Py_ssize_t f_stride = 0 - * - * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":1125 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1126 - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1127 - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - goto __pyx_L4_break; - - /* "View.MemoryView":1125 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L4_break:; - - /* "View.MemoryView":1129 - * break - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] - */ - __pyx_t_1 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_1; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1130 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1131 - * for i in range(ndim): - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1132 - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - */ - goto __pyx_L7_break; - - /* "View.MemoryView":1130 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L7_break:; - - /* "View.MemoryView":1134 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1135 - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - * return 'C' # <<<<<<<<<<<<<< - * else: - * return 'F' - */ - __pyx_r = 'C'; - goto __pyx_L0; - - /* "View.MemoryView":1134 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - } - - /* "View.MemoryView":1137 - * return 'C' - * else: - * return 'F' # <<<<<<<<<<<<<< - * - * @cython.cdivision(True) - */ - /*else*/ { - __pyx_r = 'F'; - goto __pyx_L0; - } - - /* "View.MemoryView":1116 - * - * @cname('__pyx_get_best_slice_order') - * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< - * """ - * Figure out the best memory access order for a given slice. - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1140 - * - * @cython.cdivision(True) - * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< - * char *dst_data, Py_ssize_t *dst_strides, - * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - */ - -static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; - Py_ssize_t __pyx_v_dst_extent; - Py_ssize_t __pyx_v_src_stride; - Py_ssize_t __pyx_v_dst_stride; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - - /* "View.MemoryView":1147 - * - * cdef Py_ssize_t i - * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] - */ - __pyx_v_src_extent = (__pyx_v_src_shape[0]); - - /* "View.MemoryView":1148 - * cdef Py_ssize_t i - * cdef Py_ssize_t src_extent = src_shape[0] - * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t src_stride = src_strides[0] - * cdef Py_ssize_t dst_stride = dst_strides[0] - */ - __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); - - /* "View.MemoryView":1149 - * cdef Py_ssize_t src_extent = src_shape[0] - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - */ - __pyx_v_src_stride = (__pyx_v_src_strides[0]); - - /* "View.MemoryView":1150 - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] - * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< - * - * if ndim == 1: - */ - __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); - - /* "View.MemoryView":1152 - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - */ - __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1153 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L5_bool_binop_done; - } - - /* "View.MemoryView":1154 - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< - * memcpy(dst_data, src_data, itemsize * dst_extent) - * else: - */ - __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); - if (__pyx_t_2) { - __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); - } - __pyx_t_3 = (__pyx_t_2 != 0); - __pyx_t_1 = __pyx_t_3; - __pyx_L5_bool_binop_done:; - - /* "View.MemoryView":1153 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - if (__pyx_t_1) { - - /* "View.MemoryView":1155 - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< - * else: - * for i in range(dst_extent): - */ - (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); - - /* "View.MemoryView":1153 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1157 - * memcpy(dst_data, src_data, itemsize * dst_extent) - * else: - * for i in range(dst_extent): # <<<<<<<<<<<<<< - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride - */ - /*else*/ { - __pyx_t_4 = __pyx_v_dst_extent; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1158 - * else: - * for i in range(dst_extent): - * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< - * src_data += src_stride - * dst_data += dst_stride - */ - (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); - - /* "View.MemoryView":1159 - * for i in range(dst_extent): - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride # <<<<<<<<<<<<<< - * dst_data += dst_stride - * else: - */ - __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - - /* "View.MemoryView":1160 - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride - * dst_data += dst_stride # <<<<<<<<<<<<<< - * else: - * for i in range(dst_extent): - */ - __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); - } - } - __pyx_L4:; - - /* "View.MemoryView":1152 - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1162 - * dst_data += dst_stride - * else: - * for i in range(dst_extent): # <<<<<<<<<<<<<< - * _copy_strided_to_strided(src_data, src_strides + 1, - * dst_data, dst_strides + 1, - */ - /*else*/ { - __pyx_t_4 = __pyx_v_dst_extent; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1163 - * else: - * for i in range(dst_extent): - * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< - * dst_data, dst_strides + 1, - * src_shape + 1, dst_shape + 1, - */ - _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); - - /* "View.MemoryView":1167 - * src_shape + 1, dst_shape + 1, - * ndim - 1, itemsize) - * src_data += src_stride # <<<<<<<<<<<<<< - * dst_data += dst_stride - * - */ - __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - - /* "View.MemoryView":1168 - * ndim - 1, itemsize) - * src_data += src_stride - * dst_data += dst_stride # <<<<<<<<<<<<<< - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, - */ - __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); - } - } - __pyx_L3:; - - /* "View.MemoryView":1140 - * - * @cython.cdivision(True) - * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< - * char *dst_data, Py_ssize_t *dst_strides, - * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - */ - - /* function exit code */ -} - -/* "View.MemoryView":1170 - * dst_data += dst_stride - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - */ - -static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - - /* "View.MemoryView":1173 - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< - * src.shape, dst.shape, ndim, itemsize) - * - */ - _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); - - /* "View.MemoryView":1170 - * dst_data += dst_stride - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1177 - * - * @cname('__pyx_memoryview_slice_get_size') - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - */ - -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { - Py_ssize_t __pyx_v_shape; - Py_ssize_t __pyx_v_size; - Py_ssize_t __pyx_r; - Py_ssize_t __pyx_t_1; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - - /* "View.MemoryView":1179 - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize # <<<<<<<<<<<<<< - * - * for shape in src.shape[:ndim]: - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_size = __pyx_t_1; - - /* "View.MemoryView":1181 - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - * - * for shape in src.shape[:ndim]: # <<<<<<<<<<<<<< - * size *= shape - * - */ - __pyx_t_3 = (__pyx_v_src->shape + __pyx_v_ndim); - for (__pyx_t_4 = __pyx_v_src->shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { - __pyx_t_2 = __pyx_t_4; - __pyx_v_shape = (__pyx_t_2[0]); - - /* "View.MemoryView":1182 - * - * for shape in src.shape[:ndim]: - * size *= shape # <<<<<<<<<<<<<< - * - * return size - */ - __pyx_v_size = (__pyx_v_size * __pyx_v_shape); - } - - /* "View.MemoryView":1184 - * size *= shape - * - * return size # <<<<<<<<<<<<<< - * - * @cname('__pyx_fill_contig_strides_array') - */ - __pyx_r = __pyx_v_size; - goto __pyx_L0; - - /* "View.MemoryView":1177 - * - * @cname('__pyx_memoryview_slice_get_size') - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1187 - * - * @cname('__pyx_fill_contig_strides_array') - * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< - * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - * int ndim, char order) nogil: - */ - -static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { - int __pyx_v_idx; - Py_ssize_t __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1196 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - __pyx_t_1 = ((__pyx_v_order == 'F') != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1197 - * - * if order == 'F': - * for idx in range(ndim): # <<<<<<<<<<<<<< - * strides[idx] = stride - * stride *= shape[idx] - */ - __pyx_t_2 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_idx = __pyx_t_4; - - /* "View.MemoryView":1198 - * if order == 'F': - * for idx in range(ndim): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride *= shape[idx] - * else: - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1199 - * for idx in range(ndim): - * strides[idx] = stride - * stride *= shape[idx] # <<<<<<<<<<<<<< - * else: - * for idx in range(ndim - 1, -1, -1): - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - - /* "View.MemoryView":1196 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1201 - * stride *= shape[idx] - * else: - * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * strides[idx] = stride - * stride *= shape[idx] - */ - /*else*/ { - for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { - __pyx_v_idx = __pyx_t_2; - - /* "View.MemoryView":1202 - * else: - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride *= shape[idx] - * - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1203 - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride - * stride *= shape[idx] # <<<<<<<<<<<<<< - * - * return stride - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - } - __pyx_L3:; - - /* "View.MemoryView":1205 - * stride *= shape[idx] - * - * return stride # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_data_to_temp') - */ - __pyx_r = __pyx_v_stride; - goto __pyx_L0; - - /* "View.MemoryView":1187 - * - * @cname('__pyx_fill_contig_strides_array') - * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< - * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - * int ndim, char order) nogil: - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1208 - * - * @cname('__pyx_memoryview_copy_data_to_temp') - * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *tmpslice, - * char order, - */ - -static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { - int __pyx_v_i; - void *__pyx_v_result; - size_t __pyx_v_itemsize; - size_t __pyx_v_size; - void *__pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - struct __pyx_memoryview_obj *__pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":1219 - * cdef void *result - * - * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< - * cdef size_t size = slice_get_size(src, ndim) - * - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":1220 - * - * cdef size_t itemsize = src.memview.view.itemsize - * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< - * - * result = malloc(size) - */ - __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); - - /* "View.MemoryView":1222 - * cdef size_t size = slice_get_size(src, ndim) - * - * result = malloc(size) # <<<<<<<<<<<<<< - * if not result: - * _err(MemoryError, NULL) - */ - __pyx_v_result = malloc(__pyx_v_size); - - /* "View.MemoryView":1223 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1224 - * result = malloc(size) - * if not result: - * _err(MemoryError, NULL) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 1224, __pyx_L1_error) - - /* "View.MemoryView":1223 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - } - - /* "View.MemoryView":1227 - * - * - * tmpslice.data = result # <<<<<<<<<<<<<< - * tmpslice.memview = src.memview - * for i in range(ndim): - */ - __pyx_v_tmpslice->data = ((char *)__pyx_v_result); - - /* "View.MemoryView":1228 - * - * tmpslice.data = result - * tmpslice.memview = src.memview # <<<<<<<<<<<<<< - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] - */ - __pyx_t_4 = __pyx_v_src->memview; - __pyx_v_tmpslice->memview = __pyx_t_4; - - /* "View.MemoryView":1229 - * tmpslice.data = result - * tmpslice.memview = src.memview - * for i in range(ndim): # <<<<<<<<<<<<<< - * tmpslice.shape[i] = src.shape[i] - * tmpslice.suboffsets[i] = -1 - */ - __pyx_t_3 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_3; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1230 - * tmpslice.memview = src.memview - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< - * tmpslice.suboffsets[i] = -1 - * - */ - (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); - - /* "View.MemoryView":1231 - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] - * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, - */ - (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1233 - * tmpslice.suboffsets[i] = -1 - * - * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< - * ndim, order) - * - */ - (void)(__pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order)); - - /* "View.MemoryView":1237 - * - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if tmpslice.shape[i] == 1: - * tmpslice.strides[i] = 0 - */ - __pyx_t_3 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_3; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1238 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1239 - * for i in range(ndim): - * if tmpslice.shape[i] == 1: - * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< - * - * if slice_is_contig(src[0], order, ndim): - */ - (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; - - /* "View.MemoryView":1238 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - } - } - - /* "View.MemoryView":1241 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1242 - * - * if slice_is_contig(src[0], order, ndim): - * memcpy(result, src.data, size) # <<<<<<<<<<<<<< - * else: - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - */ - (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); - - /* "View.MemoryView":1241 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":1244 - * memcpy(result, src.data, size) - * else: - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< - * - * return result - */ - /*else*/ { - copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); - } - __pyx_L9:; - - /* "View.MemoryView":1246 - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":1208 - * - * @cname('__pyx_memoryview_copy_data_to_temp') - * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *tmpslice, - * char order, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = NULL; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1251 - * - * @cname('__pyx_memoryview_err_extents') - * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - */ - -static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_extents", 0); - - /* "View.MemoryView":1254 - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - * (i, extent1, extent2)) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_err_dim') - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - - /* "View.MemoryView":1253 - * cdef int _err_extents(int i, Py_ssize_t extent1, - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< - * (i, extent1, extent2)) - * - */ - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1253, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1253, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(1, 1253, __pyx_L1_error) - - /* "View.MemoryView":1251 - * - * @cname('__pyx_memoryview_err_extents') - * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1257 - * - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii') % dim) - * - */ - -static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_dim", 0); - __Pyx_INCREF(__pyx_v_error); - - /* "View.MemoryView":1258 - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: - * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_err') - */ - __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_INCREF(__pyx_v_error); - __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1258, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 1258, __pyx_L1_error) - - /* "View.MemoryView":1257 - * - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii') % dim) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_XDECREF(__pyx_v_error); - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1261 - * - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< - * if msg != NULL: - * raise error(msg.decode('ascii')) - */ - -static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err", 0); - __Pyx_INCREF(__pyx_v_error); - - /* "View.MemoryView":1262 - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii')) - * else: - */ - __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":1263 - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: - * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< - * else: - * raise error - */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1263, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_error); - __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1263, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(1, 1263, __pyx_L1_error) - - /* "View.MemoryView":1262 - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii')) - * else: - */ - } - - /* "View.MemoryView":1265 - * raise error(msg.decode('ascii')) - * else: - * raise error # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_contents') - */ - /*else*/ { - __Pyx_Raise(__pyx_v_error, 0, 0, 0); - __PYX_ERR(1, 1265, __pyx_L1_error) - } - - /* "View.MemoryView":1261 - * - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< - * if msg != NULL: - * raise error(msg.decode('ascii')) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_XDECREF(__pyx_v_error); - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1268 - * - * @cname('__pyx_memoryview_copy_contents') - * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice dst, - * int src_ndim, int dst_ndim, - */ - -static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { - void *__pyx_v_tmpdata; - size_t __pyx_v_itemsize; - int __pyx_v_i; - char __pyx_v_order; - int __pyx_v_broadcasting; - int __pyx_v_direct_copy; - __Pyx_memviewslice __pyx_v_tmp; - int __pyx_v_ndim; - int __pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - void *__pyx_t_7; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":1276 - * Check for overlapping memory and verify the shapes. - * """ - * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< - * cdef size_t itemsize = src.memview.view.itemsize - * cdef int i - */ - __pyx_v_tmpdata = NULL; - - /* "View.MemoryView":1277 - * """ - * cdef void *tmpdata = NULL - * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) - */ - __pyx_t_1 = __pyx_v_src.memview->view.itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":1279 - * cdef size_t itemsize = src.memview.view.itemsize - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< - * cdef bint broadcasting = False - * cdef bint direct_copy = False - */ - __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); - - /* "View.MemoryView":1280 - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) - * cdef bint broadcasting = False # <<<<<<<<<<<<<< - * cdef bint direct_copy = False - * cdef __Pyx_memviewslice tmp - */ - __pyx_v_broadcasting = 0; - - /* "View.MemoryView":1281 - * cdef char order = get_best_order(&src, src_ndim) - * cdef bint broadcasting = False - * cdef bint direct_copy = False # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice tmp - * - */ - __pyx_v_direct_copy = 0; - - /* "View.MemoryView":1284 - * cdef __Pyx_memviewslice tmp - * - * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - */ - __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1285 - * - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< - * elif dst_ndim < src_ndim: - * broadcast_leading(&dst, dst_ndim, src_ndim) - */ - __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); - - /* "View.MemoryView":1284 - * cdef __Pyx_memviewslice tmp - * - * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1286 - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - */ - __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1287 - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< - * - * cdef int ndim = max(src_ndim, dst_ndim) - */ - __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); - - /* "View.MemoryView":1286 - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - */ - } - __pyx_L3:; - - /* "View.MemoryView":1289 - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - __pyx_t_3 = __pyx_v_dst_ndim; - __pyx_t_4 = __pyx_v_src_ndim; - if (((__pyx_t_3 > __pyx_t_4) != 0)) { - __pyx_t_5 = __pyx_t_3; - } else { - __pyx_t_5 = __pyx_t_4; - } - __pyx_v_ndim = __pyx_t_5; - - /* "View.MemoryView":1291 - * cdef int ndim = max(src_ndim, dst_ndim) - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: - */ - __pyx_t_5 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_5; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1292 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1293 - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: # <<<<<<<<<<<<<< - * broadcasting = True - * src.strides[i] = 0 - */ - __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1294 - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: - * broadcasting = True # <<<<<<<<<<<<<< - * src.strides[i] = 0 - * else: - */ - __pyx_v_broadcasting = 1; - - /* "View.MemoryView":1295 - * if src.shape[i] == 1: - * broadcasting = True - * src.strides[i] = 0 # <<<<<<<<<<<<<< - * else: - * _err_extents(i, dst.shape[i], src.shape[i]) - */ - (__pyx_v_src.strides[__pyx_v_i]) = 0; - - /* "View.MemoryView":1293 - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: # <<<<<<<<<<<<<< - * broadcasting = True - * src.strides[i] = 0 - */ - goto __pyx_L7; - } - - /* "View.MemoryView":1297 - * src.strides[i] = 0 - * else: - * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< - * - * if src.suboffsets[i] >= 0: - */ - /*else*/ { - __pyx_t_6 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 1297, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":1292 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - } - - /* "View.MemoryView":1299 - * _err_extents(i, dst.shape[i], src.shape[i]) - * - * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - */ - __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1300 - * - * if src.suboffsets[i] >= 0: - * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< - * - * if slices_overlap(&src, &dst, ndim, itemsize): - */ - __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 1300, __pyx_L1_error) - - /* "View.MemoryView":1299 - * _err_extents(i, dst.shape[i], src.shape[i]) - * - * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - */ - } - } - - /* "View.MemoryView":1302 - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< - * - * if not slice_is_contig(src, order, ndim): - */ - __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1304 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1305 - * - * if not slice_is_contig(src, order, ndim): - * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - */ - __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); - - /* "View.MemoryView":1304 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - } - - /* "View.MemoryView":1307 - * order = get_best_order(&dst, ndim) - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< - * src = tmp - * - */ - __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(1, 1307, __pyx_L1_error) - __pyx_v_tmpdata = __pyx_t_7; - - /* "View.MemoryView":1308 - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - * src = tmp # <<<<<<<<<<<<<< - * - * if not broadcasting: - */ - __pyx_v_src = __pyx_v_tmp; - - /* "View.MemoryView":1302 - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< - * - * if not slice_is_contig(src, order, ndim): - */ - } - - /* "View.MemoryView":1310 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1313 - * - * - * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1314 - * - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< - * elif slice_is_contig(src, 'F', ndim): - * direct_copy = slice_is_contig(dst, 'F', ndim) - */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); - - /* "View.MemoryView":1313 - * - * - * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - */ - goto __pyx_L12; - } - - /* "View.MemoryView":1315 - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1316 - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< - * - * if direct_copy: - */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); - - /* "View.MemoryView":1315 - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - */ - } - __pyx_L12:; - - /* "View.MemoryView":1318 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - __pyx_t_2 = (__pyx_v_direct_copy != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1320 - * if direct_copy: - * - * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1321 - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) - */ - (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); - - /* "View.MemoryView":1322 - * refcount_copying(&dst, dtype_is_object, ndim, False) - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * free(tmpdata) - * return 0 - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1323 - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1324 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * if order == 'F' == get_best_order(&dst, ndim): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1318 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - } - - /* "View.MemoryView":1310 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1326 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = (__pyx_v_order == 'F'); - if (__pyx_t_2) { - __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); - } - __pyx_t_8 = (__pyx_t_2 != 0); - if (__pyx_t_8) { - - /* "View.MemoryView":1329 - * - * - * transpose_memslice(&src) # <<<<<<<<<<<<<< - * transpose_memslice(&dst) - * - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1329, __pyx_L1_error) - - /* "View.MemoryView":1330 - * - * transpose_memslice(&src) - * transpose_memslice(&dst) # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1330, __pyx_L1_error) - - /* "View.MemoryView":1326 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1332 - * transpose_memslice(&dst) - * - * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * copy_strided_to_strided(&src, &dst, ndim, itemsize) - * refcount_copying(&dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1333 - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - */ - copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); - - /* "View.MemoryView":1334 - * refcount_copying(&dst, dtype_is_object, ndim, False) - * copy_strided_to_strided(&src, &dst, ndim, itemsize) - * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * - * free(tmpdata) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1336 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1337 - * - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_broadcast_leading') - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1268 - * - * @cname('__pyx_memoryview_copy_contents') - * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice dst, - * int src_ndim, int dst_ndim, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = -1; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1340 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { - int __pyx_v_i; - int __pyx_v_offset; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - - /* "View.MemoryView":1344 - * int ndim_other) nogil: - * cdef int i - * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< - * - * for i in range(ndim - 1, -1, -1): - */ - __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); - - /* "View.MemoryView":1346 - * cdef int offset = ndim_other - ndim - * - * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] - */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":1347 - * - * for i in range(ndim - 1, -1, -1): - * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< - * mslice.strides[i + offset] = mslice.strides[i] - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - */ - (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); - - /* "View.MemoryView":1348 - * for i in range(ndim - 1, -1, -1): - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - * - */ - (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1349 - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< - * - * for i in range(offset): - */ - (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); - } - - /* "View.MemoryView":1351 - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - * - * for i in range(offset): # <<<<<<<<<<<<<< - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - */ - __pyx_t_1 = __pyx_v_offset; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - - /* "View.MemoryView":1352 - * - * for i in range(offset): - * mslice.shape[i] = 1 # <<<<<<<<<<<<<< - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 - */ - (__pyx_v_mslice->shape[__pyx_v_i]) = 1; - - /* "View.MemoryView":1353 - * for i in range(offset): - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< - * mslice.suboffsets[i] = -1 - * - */ - (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); - - /* "View.MemoryView":1354 - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1340 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1362 - * - * @cname('__pyx_memoryview_refcount_copying') - * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< - * int ndim, bint inc) nogil: - * - */ - -static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { - int __pyx_t_1; - - /* "View.MemoryView":1366 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - __pyx_t_1 = (__pyx_v_dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1367 - * - * if dtype_is_object: - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< - * dst.strides, ndim, inc) - * - */ - __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); - - /* "View.MemoryView":1366 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - } - - /* "View.MemoryView":1362 - * - * @cname('__pyx_memoryview_refcount_copying') - * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< - * int ndim, bint inc) nogil: - * - */ - - /* function exit code */ -} - -/* "View.MemoryView":1371 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') - * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - */ - -static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { - __Pyx_RefNannyDeclarations - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); - - /* "View.MemoryView":1374 - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); - - /* "View.MemoryView":1371 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') - * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif -} - -/* "View.MemoryView":1377 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, bint inc): - * cdef Py_ssize_t i - */ - -static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); - - /* "View.MemoryView":1381 - * cdef Py_ssize_t i - * - * for i in range(shape[0]): # <<<<<<<<<<<<<< - * if ndim == 1: - * if inc: - */ - __pyx_t_1 = (__pyx_v_shape[0]); - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - - /* "View.MemoryView":1382 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1383 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - __pyx_t_4 = (__pyx_v_inc != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1384 - * if ndim == 1: - * if inc: - * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * Py_DECREF(( data)[0]) - */ - Py_INCREF((((PyObject **)__pyx_v_data)[0])); - - /* "View.MemoryView":1383 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":1386 - * Py_INCREF(( data)[0]) - * else: - * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, - */ - /*else*/ { - Py_DECREF((((PyObject **)__pyx_v_data)[0])); - } - __pyx_L6:; - - /* "View.MemoryView":1382 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - goto __pyx_L5; - } - - /* "View.MemoryView":1388 - * Py_DECREF(( data)[0]) - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, inc) - * - */ - /*else*/ { - - /* "View.MemoryView":1389 - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, - * ndim - 1, inc) # <<<<<<<<<<<<<< - * - * data += strides[0] - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); - } - __pyx_L5:; - - /* "View.MemoryView":1391 - * ndim - 1, inc) - * - * data += strides[0] # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); - } - - /* "View.MemoryView":1377 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, bint inc): - * cdef Py_ssize_t i - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":1397 - * - * @cname('__pyx_memoryview_slice_assign_scalar') - * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - */ - -static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { - - /* "View.MemoryView":1400 - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - * itemsize, item) - */ - __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1401 - * bint dtype_is_object) nogil: - * refcount_copying(dst, dtype_is_object, ndim, False) - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< - * itemsize, item) - * refcount_copying(dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); - - /* "View.MemoryView":1403 - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - * itemsize, item) - * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * - * - */ - __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1397 - * - * @cname('__pyx_memoryview_slice_assign_scalar') - * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1407 - * - * @cname('__pyx_memoryview__slice_assign_scalar') - * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * size_t itemsize, void *item) nogil: - */ - -static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - Py_ssize_t __pyx_v_stride; - Py_ssize_t __pyx_v_extent; - int __pyx_t_1; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - Py_ssize_t __pyx_t_4; - - /* "View.MemoryView":1411 - * size_t itemsize, void *item) nogil: - * cdef Py_ssize_t i - * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t extent = shape[0] - * - */ - __pyx_v_stride = (__pyx_v_strides[0]); - - /* "View.MemoryView":1412 - * cdef Py_ssize_t i - * cdef Py_ssize_t stride = strides[0] - * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< - * - * if ndim == 1: - */ - __pyx_v_extent = (__pyx_v_shape[0]); - - /* "View.MemoryView":1414 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1415 - * - * if ndim == 1: - * for i in range(extent): # <<<<<<<<<<<<<< - * memcpy(data, item, itemsize) - * data += stride - */ - __pyx_t_2 = __pyx_v_extent; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1416 - * if ndim == 1: - * for i in range(extent): - * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< - * data += stride - * else: - */ - (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); - - /* "View.MemoryView":1417 - * for i in range(extent): - * memcpy(data, item, itemsize) - * data += stride # <<<<<<<<<<<<<< - * else: - * for i in range(extent): - */ - __pyx_v_data = (__pyx_v_data + __pyx_v_stride); - } - - /* "View.MemoryView":1414 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1419 - * data += stride - * else: - * for i in range(extent): # <<<<<<<<<<<<<< - * _slice_assign_scalar(data, shape + 1, strides + 1, - * ndim - 1, itemsize, item) - */ - /*else*/ { - __pyx_t_2 = __pyx_v_extent; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1420 - * else: - * for i in range(extent): - * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, itemsize, item) - * data += stride - */ - __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); - - /* "View.MemoryView":1422 - * _slice_assign_scalar(data, shape + 1, strides + 1, - * ndim - 1, itemsize, item) - * data += stride # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + __pyx_v_stride); - } - } - __pyx_L3:; - - /* "View.MemoryView":1407 - * - * @cname('__pyx_memoryview__slice_assign_scalar') - * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * size_t itemsize, void *item) nogil: - */ - - /* function exit code */ -} - -/* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v___pyx_type = 0; - long __pyx_v___pyx_checksum; - PyObject *__pyx_v___pyx_state = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v___pyx_type = values[0]; - __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_v___pyx_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_v___pyx_PickleError = 0; - PyObject *__pyx_v___pyx_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - */ - __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); - if (__pyx_t_1) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); - __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_2); - __pyx_v___pyx_PickleError = __pyx_t_2; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum != 0xb068931: - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v___pyx_result = __pyx_t_3; - __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - __pyx_t_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_6 = (__pyx_t_1 != 0); - if (__pyx_t_6) { - - /* "(tree fragment)":9 - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - } - - /* "(tree fragment)":10 - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result # <<<<<<<<<<<<<< - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v___pyx_result); - __pyx_r = __pyx_v___pyx_result; - goto __pyx_L0; - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v___pyx_PickleError); - __Pyx_XDECREF(__pyx_v___pyx_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - -static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); - - /* "(tree fragment)":12 - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->name); - __Pyx_DECREF(__pyx_v___pyx_result->name); - __pyx_v___pyx_result->name = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 13, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_4 = ((__pyx_t_3 > 1) != 0); - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L4_bool_binop_done:; - if (__pyx_t_2) { - - /* "(tree fragment)":14 - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< - */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 14, __pyx_L1_error) - } - __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - } - - /* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static struct __pyx_vtabstruct_array __pyx_vtable_array; - -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_array_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_array_obj *)o); - p->__pyx_vtab = __pyx_vtabptr_array; - p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_array(PyObject *o) { - struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_array___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->mode); - Py_CLEAR(p->_format); - (*Py_TYPE(o)->tp_free)(o); -} -static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_array___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } -} - -static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { - PyObject *v = __Pyx_PyObject_GenericGetAttr(o, n); - if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - v = __pyx_array___getattr__(o, n); - } - return v; -} - -static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); -} - -static PyMethodDef __pyx_methods_array[] = { - {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_array[] = { - {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence_array = { - __pyx_array___len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_array, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_array = { - __pyx_array___len__, /*mp_length*/ - __pyx_array___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_array = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_array_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; - -static PyTypeObject __pyx_type___pyx_array = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core.array", /*tp_name*/ - sizeof(struct __pyx_array_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_array, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - __pyx_tp_getattro_array, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_array, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_array, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_array, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_MemviewEnum_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_MemviewEnum_obj *)o); - p->name = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_Enum(PyObject *o) { - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->name); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - if (p->name) { - e = (*v)(p->name, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_Enum(PyObject *o) { - PyObject* tmp; - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - tmp = ((PyObject*)p->name); - p->name = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_Enum[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type___pyx_MemviewEnum = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core.Enum", /*tp_name*/ - sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_Enum, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_MemviewEnum___repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_Enum, /*tp_traverse*/ - __pyx_tp_clear_Enum, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_Enum, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_MemviewEnum___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_Enum, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; - -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_memoryview_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_memoryview_obj *)o); - p->__pyx_vtab = __pyx_vtabptr_memoryview; - p->obj = Py_None; Py_INCREF(Py_None); - p->_size = Py_None; Py_INCREF(Py_None); - p->_array_interface = Py_None; Py_INCREF(Py_None); - p->view.obj = NULL; - if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_memoryview(PyObject *o) { - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_memoryview___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->obj); - Py_CLEAR(p->_size); - Py_CLEAR(p->_array_interface); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - if (p->obj) { - e = (*v)(p->obj, a); if (e) return e; - } - if (p->_size) { - e = (*v)(p->_size, a); if (e) return e; - } - if (p->_array_interface) { - e = (*v)(p->_array_interface, a); if (e) return e; - } - if (p->view.obj) { - e = (*v)(p->view.obj, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_memoryview(PyObject *o) { - PyObject* tmp; - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - tmp = ((PyObject*)p->obj); - p->obj = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_size); - p->_size = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_array_interface); - p->_array_interface = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - Py_CLEAR(p->view.obj); - return 0; -} -static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_memoryview___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } -} - -static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(o); -} - -static PyMethodDef __pyx_methods_memoryview[] = { - {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, - {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, - {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, - {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_memoryview[] = { - {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, - {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, - {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, - {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, - {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, - {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, - {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, - {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, - {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence_memoryview = { - __pyx_memoryview___len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_memoryview, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_memoryview = { - __pyx_memoryview___len__, /*mp_length*/ - __pyx_memoryview___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_memoryview = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_memoryview_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; - -static PyTypeObject __pyx_type___pyx_memoryview = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core.memoryview", /*tp_name*/ - sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_memoryview___repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - __pyx_memoryview___str__, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_memoryview, /*tp_traverse*/ - __pyx_tp_clear_memoryview, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_memoryview, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_memoryview, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_memoryview, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; - -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_memoryviewslice_obj *p; - PyObject *o = __pyx_tp_new_memoryview(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_memoryviewslice_obj *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; - p->from_object = Py_None; Py_INCREF(Py_None); - p->from_slice.memview = NULL; - return o; -} - -static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_memoryviewslice___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->from_object); - PyObject_GC_Track(o); - __pyx_tp_dealloc_memoryview(o); -} - -static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; - if (p->from_object) { - e = (*v)(p->from_object, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear__memoryviewslice(PyObject *o) { - PyObject* tmp; - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - __pyx_tp_clear_memoryview(o); - tmp = ((PyObject*)p->from_object); - p->from_object = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - __PYX_XDEC_MEMVIEW(&p->from_slice, 1); - return 0; -} - -static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); -} - -static PyMethodDef __pyx_methods__memoryviewslice[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { - {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type___pyx_memoryviewslice = { - PyVarObject_HEAD_INIT(0, 0) - "monotonic_align.core._memoryviewslice", /*tp_name*/ - sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_memoryview___repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_memoryview___str__, /*tp_str*/ - #else - 0, /*tp_str*/ - #endif - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - "Internal class for passing memoryview slices to Python", /*tp_doc*/ - __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ - __pyx_tp_clear__memoryviewslice, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods__memoryviewslice, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets__memoryviewslice, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new__memoryviewslice, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {"maximum_path_c", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15monotonic_align_4core_1maximum_path_c, METH_VARARGS|METH_KEYWORDS, 0}, - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec_core(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec_core}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "core", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, - {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, - {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, - {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, - {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, - {&__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 0, 0, 1, 0}, - {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, - {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, - {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, - {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, - {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, - {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, - {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, - {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, - {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, - {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, - {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, - {&__pyx_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, - {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, - {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, - {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, - {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, - {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, - {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, - {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, - {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, - {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, - {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, - {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, - {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, - {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, - {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, - {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, - {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, - {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, - {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, - {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, - {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, - {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, - {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, - {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, - {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, - {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, - {&__pyx_n_s_paths, __pyx_k_paths, sizeof(__pyx_k_paths), 0, 0, 1, 1}, - {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, - {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, - {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, - {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, - {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, - {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, - {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, - {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, - {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, - {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, - {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, - {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, - {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, - {&__pyx_n_s_t_xs, __pyx_k_t_xs, sizeof(__pyx_k_t_xs), 0, 0, 1, 1}, - {&__pyx_n_s_t_ys, __pyx_k_t_ys, sizeof(__pyx_k_t_ys), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, - {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, - {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, - {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, - {&__pyx_n_s_values, __pyx_k_values, sizeof(__pyx_k_values), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 15, __pyx_L1_error) - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 133, __pyx_L1_error) - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 148, __pyx_L1_error) - __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 151, __pyx_L1_error) - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) - __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 404, __pyx_L1_error) - __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 613, __pyx_L1_error) - __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 832, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "View.MemoryView":133 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - - /* "View.MemoryView":136 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); - - /* "View.MemoryView":148 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - - /* "View.MemoryView":176 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 176, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "View.MemoryView":192 - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< - * info.buf = self.data - * info.len = self.len - */ - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - - /* "View.MemoryView":418 - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< - * - * have_slices, index = _unellipsify(index, self.view.ndim) - */ - __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 418, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__9); - __Pyx_GIVEREF(__pyx_tuple__9); - - /* "View.MemoryView":495 - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< - * else: - * if len(self.view.format) == 1: - */ - __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 495, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - - /* "View.MemoryView":520 - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< - * - * if flags & PyBUF_ND: - */ - __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); - - /* "View.MemoryView":570 - * if self.view.strides == NULL: - * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - */ - __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 570, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); - - /* "View.MemoryView":577 - * def suboffsets(self): - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - */ - __pyx_tuple__13 = PyTuple_New(1); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_INCREF(__pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_tuple__13, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_tuple__13); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_GIVEREF(__pyx_tuple__14); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__15); - __Pyx_GIVEREF(__pyx_tuple__15); - - /* "View.MemoryView":682 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_slice__16 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__16)) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_GOTREF(__pyx_slice__16); - __Pyx_GIVEREF(__pyx_slice__16); - - /* "View.MemoryView":703 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(1, 703, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__17); - __Pyx_GIVEREF(__pyx_tuple__17); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__18); - __Pyx_GIVEREF(__pyx_tuple__18); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__19); - __Pyx_GIVEREF(__pyx_tuple__19); - - /* "View.MemoryView":286 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(1, 286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__20); - __Pyx_GIVEREF(__pyx_tuple__20); - - /* "View.MemoryView":287 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(1, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); - - /* "View.MemoryView":288 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(1, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__22); - __Pyx_GIVEREF(__pyx_tuple__22); - - /* "View.MemoryView":291 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(1, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__23); - __Pyx_GIVEREF(__pyx_tuple__23); - - /* "View.MemoryView":292 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(1, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__24); - __Pyx_GIVEREF(__pyx_tuple__24); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_tuple__25 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__25); - __Pyx_GIVEREF(__pyx_tuple__25); - __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__25, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - /* InitThreads.init */ - #ifdef WITH_THREAD -PyEval_InitThreads(); -#endif - -if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) - - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - generic = Py_None; Py_INCREF(Py_None); - strided = Py_None; Py_INCREF(Py_None); - indirect = Py_None; Py_INCREF(Py_None); - contiguous = Py_None; Py_INCREF(Py_None); - indirect_contiguous = Py_None; Py_INCREF(Py_None); - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __pyx_vtabptr_array = &__pyx_vtable_array; - __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; - if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_array.tp_print = 0; - #endif - if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - __pyx_array_type = &__pyx_type___pyx_array; - if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_MemviewEnum.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __pyx_L1_error) - __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; - __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; - __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; - __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; - __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; - __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; - __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; - __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; - __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; - if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_memoryview.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) - __pyx_memoryview_type = &__pyx_type___pyx_memoryview; - __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; - __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; - __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; - __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; - __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; - if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_memoryviewslice.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) - __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC initcore(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC initcore(void) -#else -__Pyx_PyMODINIT_FUNC PyInit_core(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit_core(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec_core(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - static PyThread_type_lock __pyx_t_2[8]; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module 'core' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_core(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("core", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_monotonic_align__core) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "monotonic_align.core")) { - if (unlikely(PyDict_SetItemString(modules, "monotonic_align.core", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_type_import_code(); - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "monotonic_align/core.pyx":7 - * @cython.boundscheck(False) - * @cython.wraparound(False) - * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< - * cdef int x - * cdef int y - */ - __pyx_k_ = (-1e9); - - /* "monotonic_align/core.pyx":1 - * cimport cython # <<<<<<<<<<<<<< - * from cython.parallel import prange - * - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":209 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * def __dealloc__(array self): - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 209, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_array_type); - - /* "View.MemoryView":286 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(generic); - __Pyx_DECREF_SET(generic, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":287 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(strided); - __Pyx_DECREF_SET(strided, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":288 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(indirect); - __Pyx_DECREF_SET(indirect, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":291 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(contiguous); - __Pyx_DECREF_SET(contiguous, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":292 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(indirect_contiguous); - __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":316 - * - * DEF THREAD_LOCKS_PREALLOCATED = 8 - * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< - * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ - * PyThread_allocate_lock(), - */ - __pyx_memoryview_thread_locks_used = 0; - - /* "View.MemoryView":317 - * DEF THREAD_LOCKS_PREALLOCATED = 8 - * cdef int __pyx_memoryview_thread_locks_used = 0 - * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< - * PyThread_allocate_lock(), - * PyThread_allocate_lock(), - */ - __pyx_t_2[0] = PyThread_allocate_lock(); - __pyx_t_2[1] = PyThread_allocate_lock(); - __pyx_t_2[2] = PyThread_allocate_lock(); - __pyx_t_2[3] = PyThread_allocate_lock(); - __pyx_t_2[4] = PyThread_allocate_lock(); - __pyx_t_2[5] = PyThread_allocate_lock(); - __pyx_t_2[6] = PyThread_allocate_lock(); - __pyx_t_2[7] = PyThread_allocate_lock(); - memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); - - /* "View.MemoryView":549 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 549, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_memoryview_type); - - /* "View.MemoryView":995 - * return self.from_object - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 995, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 995, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_memoryviewslice_type); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init monotonic_align.core", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init monotonic_align.core"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* MemviewSliceInit */ -static int -__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference) -{ - __Pyx_RefNannyDeclarations - int i, retval=-1; - Py_buffer *buf = &memview->view; - __Pyx_RefNannySetupContext("init_memviewslice", 0); - if (unlikely(memviewslice->memview || memviewslice->data)) { - PyErr_SetString(PyExc_ValueError, - "memviewslice is already initialized!"); - goto fail; - } - if (buf->strides) { - for (i = 0; i < ndim; i++) { - memviewslice->strides[i] = buf->strides[i]; - } - } else { - Py_ssize_t stride = buf->itemsize; - for (i = ndim - 1; i >= 0; i--) { - memviewslice->strides[i] = stride; - stride *= buf->shape[i]; - } - } - for (i = 0; i < ndim; i++) { - memviewslice->shape[i] = buf->shape[i]; - if (buf->suboffsets) { - memviewslice->suboffsets[i] = buf->suboffsets[i]; - } else { - memviewslice->suboffsets[i] = -1; - } - } - memviewslice->memview = memview; - memviewslice->data = (char *)buf->buf; - if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { - Py_INCREF(memview); - } - retval = 0; - goto no_fail; -fail: - memviewslice->memview = 0; - memviewslice->data = 0; - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} -#ifndef Py_NO_RETURN -#define Py_NO_RETURN -#endif -static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { - va_list vargs; - char msg[200]; -#ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, fmt); -#else - va_start(vargs); -#endif - vsnprintf(msg, 200, fmt, vargs); - va_end(vargs); - Py_FatalError(msg); -} -static CYTHON_INLINE int -__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)++; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE int -__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)--; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE void -__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) -{ - int first_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (unlikely(!memview || (PyObject *) memview == Py_None)) - return; - if (unlikely(__pyx_get_slice_count(memview) < 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - first_time = __pyx_add_acquisition_count(memview) == 0; - if (unlikely(first_time)) { - if (have_gil) { - Py_INCREF((PyObject *) memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_INCREF((PyObject *) memview); - PyGILState_Release(_gilstate); - } - } -} -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, - int have_gil, int lineno) { - int last_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (unlikely(!memview || (PyObject *) memview == Py_None)) { - memslice->memview = NULL; - return; - } - if (unlikely(__pyx_get_slice_count(memview) <= 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - last_time = __pyx_sub_acquisition_count(memview) == 1; - memslice->data = NULL; - if (unlikely(last_time)) { - if (have_gil) { - Py_CLEAR(memslice->memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_CLEAR(memslice->memview); - PyGILState_Release(_gilstate); - } - } else { - memslice->memview = NULL; - } -} - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* None */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { - PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); -} - -/* ArgTypeTest */ -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - else if (exact) { - #if PY_MAJOR_VERSION == 2 - if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(__Pyx_TypeCheck(obj, type))) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = func->ob_type->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall2Args */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* BytesEquals */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else - if (s1 == s2) { - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { - int result; -#if CYTHON_USE_UNICODE_INTERNALS - Py_hash_t hash1, hash2; - hash1 = ((PyBytesObject*)s1)->ob_shash; - hash2 = ((PyBytesObject*)s2)->ob_shash; - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - return (equals == Py_NE); - } -#endif - result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -#endif -} - -/* UnicodeEquals */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - goto return_eq; - } - s1_is_unicode = PyUnicode_CheckExact(s1); - s2_is_unicode = PyUnicode_CheckExact(s2); -#if PY_MAJOR_VERSION < 3 - if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { - owned_ref = PyUnicode_FromObject(s2); - if (unlikely(!owned_ref)) - return -1; - s2 = owned_ref; - s2_is_unicode = 1; - } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { - owned_ref = PyUnicode_FromObject(s1); - if (unlikely(!owned_ref)) - return -1; - s1 = owned_ref; - s1_is_unicode = 1; - } else if (((!s2_is_unicode) & (!s1_is_unicode))) { - return __Pyx_PyBytes_Equals(s1, s2, equals); - } -#endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } -#if CYTHON_USE_UNICODE_INTERNALS - { - Py_hash_t hash1, hash2; - #if CYTHON_PEP393_ENABLED - hash1 = ((PyASCIIObject*)s1)->hash; - hash2 = ((PyASCIIObject*)s2)->hash; - #else - hash1 = ((PyUnicodeObject*)s1)->hash; - hash2 = ((PyUnicodeObject*)s2)->hash; - #endif - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - goto return_ne; - } - } -#endif - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); -#endif -} - -/* None */ -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { - Py_ssize_t q = a / b; - Py_ssize_t r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - -/* GetAttr */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/* GetItemInt */ -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyList_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyTuple_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/* ObjectGetItem */ -#if CYTHON_USE_TYPE_SLOTS -static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { - PyObject *runerr; - Py_ssize_t key_value; - PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; - if (unlikely(!(m && m->sq_item))) { - PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); - return NULL; - } - key_value = __Pyx_PyIndex_AsSsize_t(index); - if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { - return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); - } - if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); - } - return NULL; -} -static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { - PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; - if (likely(m && m->mp_subscript)) { - return m->mp_subscript(obj, key); - } - return __Pyx_PyObject_GetIndex(obj, key); -} -#endif - -/* decode_c_string */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - Py_ssize_t length; - if (unlikely((start < 0) | (stop < 0))) { - size_t slen = strlen(cstring); - if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { - PyErr_SetString(PyExc_OverflowError, - "c-string too long to convert to Python"); - return NULL; - } - length = (Py_ssize_t) slen; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - if (unlikely(stop <= start)) - return __Pyx_NewRef(__pyx_empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/* PyErrExceptionMatches */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; icurexc_type; - if (exc_type == err) return 1; - if (unlikely(!exc_type)) return 0; - if (unlikely(PyTuple_Check(err))) - return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); - return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); -} -#endif - -/* GetAttr3 */ -static PyObject *__Pyx_GetAttr3Default(PyObject *d) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(d); - return d; -} -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); - return (likely(r)) ? r : __Pyx_GetAttr3Default(d); -} - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ -#if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* RaiseTooManyValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/* RaiseNeedMoreValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/* RaiseNoneIterError */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* ExtTypeTest */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(__Pyx_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -/* GetTopmostException */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* SaveResetException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* GetException */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* SwapException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = *type; - exc_info->exc_value = *value; - exc_info->exc_traceback = *tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = *type; - tstate->exc_value = *value; - tstate->exc_traceback = *tb; - #endif - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); - PyErr_SetExcInfo(*type, *value, *tb); - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#endif - -/* Import */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; i= 0 || (x^b) >= 0)) - return PyInt_FromLong(x); - return PyLong_Type.tp_as_number->nb_add(op1, op2); - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a, x; -#ifdef HAVE_LONG_LONG - const PY_LONG_LONG llb = intval; - PY_LONG_LONG lla, llx; -#endif - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - if (likely(__Pyx_sst_abs(size) <= 1)) { - a = likely(size) ? digits[0] : 0; - if (size == -1) a = -a; - } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - default: return PyLong_Type.tp_as_number->nb_add(op1, op2); - } - } - x = a + b; - return PyLong_FromLong(x); -#ifdef HAVE_LONG_LONG - long_long: - llx = lla + llb; - return PyLong_FromLongLong(llx); -#endif - - - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - double result; - PyFPE_START_PROTECT("add", return NULL) - result = ((double)a) + (double)b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); - } - return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); -} -#endif - -/* None */ -static CYTHON_INLINE long __Pyx_div_long(long a, long b) { - long q = a / b; - long r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - -/* ImportFrom */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* HasAttr */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { - PyObject *r; - if (unlikely(!__Pyx_PyBaseString_Check(n))) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return -1; - } - r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); - return 0; - } else { - Py_DECREF(r); - return 1; - } -} - -/* PyObject_GenericGetAttrNoDict */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, attr_name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(attr_name)); -#endif - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { - PyObject *descr; - PyTypeObject *tp = Py_TYPE(obj); - if (unlikely(!PyString_Check(attr_name))) { - return PyObject_GenericGetAttr(obj, attr_name); - } - assert(!tp->tp_dictoffset); - descr = _PyType_Lookup(tp, attr_name); - if (unlikely(!descr)) { - return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); - } - Py_INCREF(descr); - #if PY_MAJOR_VERSION < 3 - if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) - #endif - { - descrgetfunc f = Py_TYPE(descr)->tp_descr_get; - if (unlikely(f)) { - PyObject *res = f(descr, obj, (PyObject *)tp); - Py_DECREF(descr); - return res; - } - } - return descr; -} -#endif - -/* PyObject_GenericGetAttr */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { - if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { - return PyObject_GenericGetAttr(obj, attr_name); - } - return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); -} -#endif - -/* SetVTable */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - -/* PyObjectGetAttrStrNoError */ -static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - __Pyx_PyErr_Clear(); -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { - return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); - } -#endif - result = __Pyx_PyObject_GetAttrStr(obj, attr_name); - if (unlikely(!result)) { - __Pyx_PyObject_GetAttrStr_ClearAttributeError(); - } - return result; -} - -/* SetupReduce */ -static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { - int ret; - PyObject *name_attr; - name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); - if (likely(name_attr)) { - ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); - } else { - ret = -1; - } - if (unlikely(ret < 0)) { - PyErr_Clear(); - ret = 0; - } - Py_XDECREF(name_attr); - return ret; -} -static int __Pyx_setup_reduce(PyObject* type_obj) { - int ret = 0; - PyObject *object_reduce = NULL; - PyObject *object_reduce_ex = NULL; - PyObject *reduce = NULL; - PyObject *reduce_ex = NULL; - PyObject *reduce_cython = NULL; - PyObject *setstate = NULL; - PyObject *setstate_cython = NULL; -#if CYTHON_USE_PYTYPE_LOOKUP - if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#else - if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#endif -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#else - object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#endif - reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; - if (reduce_ex == object_reduce_ex) { -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#else - object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#endif - reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; - if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { - reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); - if (likely(reduce_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (reduce == object_reduce || PyErr_Occurred()) { - goto __PYX_BAD; - } - setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); - if (!setstate) PyErr_Clear(); - if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { - setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); - if (likely(setstate_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (!setstate || PyErr_Occurred()) { - goto __PYX_BAD; - } - } - PyType_Modified((PyTypeObject*)type_obj); - } - } - goto __PYX_GOOD; -__PYX_BAD: - if (!PyErr_Occurred()) - PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); - ret = -1; -__PYX_GOOD: -#if !CYTHON_USE_PYTYPE_LOOKUP - Py_XDECREF(object_reduce); - Py_XDECREF(object_reduce_ex); -#endif - Py_XDECREF(reduce); - Py_XDECREF(reduce_ex); - Py_XDECREF(reduce_cython); - Py_XDECREF(setstate); - Py_XDECREF(setstate_cython); - return ret; -} - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); - PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; -} -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - if (!obj) return; - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; - } - if ((0)) {} - view->obj = NULL; - Py_DECREF(obj); -} -#endif - - -/* MemviewSliceIsContig */ -static int -__pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim) -{ - int i, index, step, start; - Py_ssize_t itemsize = mvs.memview->view.itemsize; - if (order == 'F') { - step = 1; - start = 0; - } else { - step = -1; - start = ndim - 1; - } - for (i = 0; i < ndim; i++) { - index = start + step * i; - if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) - return 0; - itemsize *= mvs.shape[index]; - } - return 1; -} - -/* OverlappingSlices */ -static void -__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, - void **out_start, void **out_end, - int ndim, size_t itemsize) -{ - char *start, *end; - int i; - start = end = slice->data; - for (i = 0; i < ndim; i++) { - Py_ssize_t stride = slice->strides[i]; - Py_ssize_t extent = slice->shape[i]; - if (extent == 0) { - *out_start = *out_end = start; - return; - } else { - if (stride > 0) - end += stride * (extent - 1); - else - start += stride * (extent - 1); - } - } - *out_start = start; - *out_end = end + itemsize; -} -static int -__pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize) -{ - void *start1, *end1, *start2, *end2; - __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); - __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); - return (start1 < end2) && (start2 < end1); -} - -/* Capsule */ -static CYTHON_INLINE PyObject * -__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) -{ - PyObject *cobj; -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(p, sig, NULL); -#else - cobj = PyCObject_FromVoidPtr(p, NULL); -#endif - return cobj; -} - -/* IsLittleEndian */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) -{ - union { - uint32_t u32; - uint8_t u8[4]; - } S; - S.u32 = 0x01020304; - return S.u8[0] == 4; -} - -/* BufferFormatCheck */ -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t <= '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case '?': return "'bool'"; - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } -} -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } -} -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; - } - } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; - } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); - } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); - } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); - } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; - } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; -} -static PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number, ndim; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ndim = ctx->head->field->type->ndim; - while (*ts && *ts != ')') { - switch (*ts) { - case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; - default: break; - } - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); - return NULL; - } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; -} -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case '\r': - case '\n': - ++ts; - break; - case '<': - if (!__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } - CYTHON_FALLTHROUGH; - case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 'p': - if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && - (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { - ctx->enc_count += ctx->new_count; - ctx->new_count = 1; - got_Z = 0; - ++ts; - break; - } - CYTHON_FALLTHROUGH; - case 's': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; - } - } - } -} - -/* TypeInfoCompare */ - static int -__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) -{ - int i; - if (!a || !b) - return 0; - if (a == b) - return 1; - if (a->size != b->size || a->typegroup != b->typegroup || - a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { - if (a->typegroup == 'H' || b->typegroup == 'H') { - return a->size == b->size; - } else { - return 0; - } - } - if (a->ndim) { - for (i = 0; i < a->ndim; i++) - if (a->arraysize[i] != b->arraysize[i]) - return 0; - } - if (a->typegroup == 'S') { - if (a->flags != b->flags) - return 0; - if (a->fields || b->fields) { - if (!(a->fields && b->fields)) - return 0; - for (i = 0; a->fields[i].type && b->fields[i].type; i++) { - __Pyx_StructField *field_a = a->fields + i; - __Pyx_StructField *field_b = b->fields + i; - if (field_a->offset != field_b->offset || - !__pyx_typeinfo_cmp(field_a->type, field_b->type)) - return 0; - } - return !a->fields[i].type && !b->fields[i].type; - } - } - return 1; -} - -/* MemviewSliceValidateAndInit */ - static int -__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) -{ - if (buf->shape[dim] <= 1) - return 1; - if (buf->strides) { - if (spec & __Pyx_MEMVIEW_CONTIG) { - if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { - if (unlikely(buf->strides[dim] != sizeof(void *))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly contiguous " - "in dimension %d.", dim); - goto fail; - } - } else if (unlikely(buf->strides[dim] != buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - if (spec & __Pyx_MEMVIEW_FOLLOW) { - Py_ssize_t stride = buf->strides[dim]; - if (stride < 0) - stride = -stride; - if (unlikely(stride < buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - } else { - if (unlikely(spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1)) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not contiguous in " - "dimension %d", dim); - goto fail; - } else if (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not indirect in " - "dimension %d", dim); - goto fail; - } else if (unlikely(buf->suboffsets)) { - PyErr_SetString(PyExc_ValueError, - "Buffer exposes suboffsets but no strides"); - goto fail; - } - } - return 1; -fail: - return 0; -} -static int -__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) -{ - if (spec & __Pyx_MEMVIEW_DIRECT) { - if (unlikely(buf->suboffsets && buf->suboffsets[dim] >= 0)) { - PyErr_Format(PyExc_ValueError, - "Buffer not compatible with direct access " - "in dimension %d.", dim); - goto fail; - } - } - if (spec & __Pyx_MEMVIEW_PTR) { - if (unlikely(!buf->suboffsets || (buf->suboffsets[dim] < 0))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly accessible " - "in dimension %d.", dim); - goto fail; - } - } - return 1; -fail: - return 0; -} -static int -__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) -{ - int i; - if (c_or_f_flag & __Pyx_IS_F_CONTIG) { - Py_ssize_t stride = 1; - for (i = 0; i < ndim; i++) { - if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not fortran contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { - Py_ssize_t stride = 1; - for (i = ndim - 1; i >- 1; i--) { - if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not C contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } - return 1; -fail: - return 0; -} -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj) -{ - struct __pyx_memoryview_obj *memview, *new_memview; - __Pyx_RefNannyDeclarations - Py_buffer *buf; - int i, spec = 0, retval = -1; - __Pyx_BufFmt_Context ctx; - int from_memoryview = __pyx_memoryview_check(original_obj); - __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); - if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) - original_obj)->typeinfo)) { - memview = (struct __pyx_memoryview_obj *) original_obj; - new_memview = NULL; - } else { - memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - original_obj, buf_flags, 0, dtype); - new_memview = memview; - if (unlikely(!memview)) - goto fail; - } - buf = &memview->view; - if (unlikely(buf->ndim != ndim)) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - ndim, buf->ndim); - goto fail; - } - if (new_memview) { - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; - } - if (unlikely((unsigned) buf->itemsize != dtype->size)) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " - "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", - buf->itemsize, - (buf->itemsize > 1) ? "s" : "", - dtype->name, - dtype->size, - (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->len > 0) { - for (i = 0; i < ndim; i++) { - spec = axes_specs[i]; - if (unlikely(!__pyx_check_strides(buf, i, ndim, spec))) - goto fail; - if (unlikely(!__pyx_check_suboffsets(buf, i, ndim, spec))) - goto fail; - } - if (unlikely(buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))) - goto fail; - } - if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, - new_memview != NULL) == -1)) { - goto fail; - } - retval = 0; - goto no_fail; -fail: - Py_XDECREF(new_memview); - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, - (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, - &__Pyx_TypeInfo_int, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, - (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, - &__Pyx_TypeInfo_float, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, - (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 1, - &__Pyx_TypeInfo_int, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -/* CIntFromPyVerify */ - #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* MemviewSliceCopyTemplate */ - static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object) -{ - __Pyx_RefNannyDeclarations - int i; - __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; - struct __pyx_memoryview_obj *from_memview = from_mvs->memview; - Py_buffer *buf = &from_memview->view; - PyObject *shape_tuple = NULL; - PyObject *temp_int = NULL; - struct __pyx_array_obj *array_obj = NULL; - struct __pyx_memoryview_obj *memview_obj = NULL; - __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); - for (i = 0; i < ndim; i++) { - if (unlikely(from_mvs->suboffsets[i] >= 0)) { - PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " - "indirect dimensions (axis %d)", i); - goto fail; - } - } - shape_tuple = PyTuple_New(ndim); - if (unlikely(!shape_tuple)) { - goto fail; - } - __Pyx_GOTREF(shape_tuple); - for(i = 0; i < ndim; i++) { - temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); - if(unlikely(!temp_int)) { - goto fail; - } else { - PyTuple_SET_ITEM(shape_tuple, i, temp_int); - temp_int = NULL; - } - } - array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); - if (unlikely(!array_obj)) { - goto fail; - } - __Pyx_GOTREF(array_obj); - memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - (PyObject *) array_obj, contig_flag, - dtype_is_object, - from_mvs->memview->typeinfo); - if (unlikely(!memview_obj)) - goto fail; - if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) - goto fail; - if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, - dtype_is_object) < 0)) - goto fail; - goto no_fail; -fail: - __Pyx_XDECREF(new_mvs.memview); - new_mvs.memview = NULL; - new_mvs.data = NULL; -no_fail: - __Pyx_XDECREF(shape_tuple); - __Pyx_XDECREF(temp_int); - __Pyx_XDECREF(array_obj); - __Pyx_RefNannyFinishContext(); - return new_mvs; -} - -/* CIntFromPy */ - static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntFromPy */ - static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { - const char neg_one = (char) ((char) 0 - (char) 1), const_zero = (char) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(char) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (char) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (char) 0; - case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) - case 2: - if (8 * sizeof(char) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { - return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(char) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { - return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(char) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { - return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (char) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(char) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (char) 0; - case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) - case -2: - if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(char) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(char) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(char) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { - return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - } -#endif - if (sizeof(char) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - char val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (char) -1; - } - } else { - char val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (char) -1; - val = __Pyx_PyInt_As_char(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to char"); - return (char) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to char"); - return (char) -1; -} - -/* CheckBinaryVersion */ - static int __Pyx_check_binary_version(void) { - char ctversion[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - return PyErr_WarnEx(NULL, message, 1); - } - return 0; -} - -/* InitStrings */ - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/spaces/simsantonioii/MusicGen-Continuation/audiocraft/quantization/__init__.py b/spaces/simsantonioii/MusicGen-Continuation/audiocraft/quantization/__init__.py deleted file mode 100644 index 836d6eb518978480c6b95d6f29ce4f84a9428793..0000000000000000000000000000000000000000 --- a/spaces/simsantonioii/MusicGen-Continuation/audiocraft/quantization/__init__.py +++ /dev/null @@ -1,9 +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. - -# flake8: noqa -from .vq import ResidualVectorQuantizer -from .base import BaseQuantizer, DummyQuantizer, QuantizedResult diff --git a/spaces/skyxx/skyxxChat/modules/config.py b/spaces/skyxx/skyxxChat/modules/config.py deleted file mode 100644 index 2eee7730787df6a857de21dbb0cbefc42cb7273d..0000000000000000000000000000000000000000 --- a/spaces/skyxx/skyxxChat/modules/config.py +++ /dev/null @@ -1,173 +0,0 @@ -from collections import defaultdict -from contextlib import contextmanager -import os -import logging -import sys -import commentjson as json - -from . import shared -from . import presets - - -__all__ = [ - "my_api_key", - "authflag", - "auth_list", - "dockerflag", - "retrieve_proxy", - "log_level", - "advance_docs", - "update_doc_config", - "multi_api_key", - "server_name", - "server_port", - "share", -] - -# 添加一个统一的config文件,避免文件过多造成的疑惑(优先级最低) -# 同时,也可以为后续支持自定义功能提供config的帮助 -if os.path.exists("config.json"): - with open("config.json", "r", encoding='utf-8') as f: - config = json.load(f) -else: - config = {} - -lang_config = config.get("language", "auto") -language = os.environ.get("LANGUAGE", lang_config) - -if os.path.exists("api_key.txt"): - logging.info("检测到api_key.txt文件,正在进行迁移...") - with open("api_key.txt", "r") as f: - config["openai_api_key"] = f.read().strip() - os.rename("api_key.txt", "api_key(deprecated).txt") - with open("config.json", "w", encoding='utf-8') as f: - json.dump(config, f, indent=4) - -if os.path.exists("auth.json"): - logging.info("检测到auth.json文件,正在进行迁移...") - auth_list = [] - with open("auth.json", "r", encoding='utf-8') as f: - auth = json.load(f) - for _ in auth: - if auth[_]["username"] and auth[_]["password"]: - auth_list.append((auth[_]["username"], auth[_]["password"])) - else: - logging.error("请检查auth.json文件中的用户名和密码!") - sys.exit(1) - config["users"] = auth_list - os.rename("auth.json", "auth(deprecated).json") - with open("config.json", "w", encoding='utf-8') as f: - json.dump(config, f, indent=4) - -## 处理docker if we are running in Docker -dockerflag = config.get("dockerflag", False) -if os.environ.get("dockerrun") == "yes": - dockerflag = True - -## 处理 api-key 以及 允许的用户列表 -my_api_key = config.get("openai_api_key", "") -my_api_key = os.environ.get("OPENAI_API_KEY", my_api_key) - -xmchat_api_key = config.get("xmchat_api_key", "") -if os.environ.get("XMCHAT_API_KEY", None) == None: - os.environ["XMCHAT_API_KEY"] = xmchat_api_key - -## 多账户机制 -multi_api_key = config.get("multi_api_key", False) # 是否开启多账户机制 -if multi_api_key: - api_key_list = config.get("api_key_list", []) - if len(api_key_list) == 0: - logging.error("多账号模式已开启,但api_key_list为空,请检查config.json") - sys.exit(1) - shared.state.set_api_key_queue(api_key_list) - -auth_list = config.get("users", []) # 实际上是使用者的列表 -authflag = len(auth_list) > 0 # 是否开启认证的状态值,改为判断auth_list长度 - -# 处理自定义的api_host,优先读环境变量的配置,如果存在则自动装配 -api_host = os.environ.get("api_host", config.get("api_host", "")) -if api_host: - shared.state.set_api_host(api_host) - -@contextmanager -def retrieve_openai_api(api_key = None): - old_api_key = os.environ.get("OPENAI_API_KEY", "") - if api_key is None: - os.environ["OPENAI_API_KEY"] = my_api_key - yield my_api_key - else: - os.environ["OPENAI_API_KEY"] = api_key - yield api_key - os.environ["OPENAI_API_KEY"] = old_api_key - -## 处理log -log_level = config.get("log_level", "INFO") -logging.basicConfig( - level=log_level, - format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s", -) - -## 处理代理: -http_proxy = config.get("http_proxy", "") -https_proxy = config.get("https_proxy", "") -http_proxy = os.environ.get("HTTP_PROXY", http_proxy) -https_proxy = os.environ.get("HTTPS_PROXY", https_proxy) - -# 重置系统变量,在不需要设置的时候不设置环境变量,以免引起全局代理报错 -os.environ["HTTP_PROXY"] = "" -os.environ["HTTPS_PROXY"] = "" - -local_embedding = config.get("local_embedding", False) # 是否使用本地embedding - -@contextmanager -def retrieve_proxy(proxy=None): - """ - 1, 如果proxy = NONE,设置环境变量,并返回最新设置的代理 - 2,如果proxy != NONE,更新当前的代理配置,但是不更新环境变量 - """ - global http_proxy, https_proxy - if proxy is not None: - http_proxy = proxy - https_proxy = proxy - yield http_proxy, https_proxy - else: - old_var = os.environ["HTTP_PROXY"], os.environ["HTTPS_PROXY"] - os.environ["HTTP_PROXY"] = http_proxy - os.environ["HTTPS_PROXY"] = https_proxy - yield http_proxy, https_proxy # return new proxy - - # return old proxy - os.environ["HTTP_PROXY"], os.environ["HTTPS_PROXY"] = old_var - - -## 处理advance docs -advance_docs = defaultdict(lambda: defaultdict(dict)) -advance_docs.update(config.get("advance_docs", {})) -def update_doc_config(two_column_pdf): - global advance_docs - advance_docs["pdf"]["two_column"] = two_column_pdf - - logging.info(f"更新后的文件参数为:{advance_docs}") - -## 处理gradio.launch参数 -server_name = config.get("server_name", None) -server_port = config.get("server_port", None) -if server_name is None: - if dockerflag: - server_name = "0.0.0.0" - else: - server_name = "127.0.0.1" -if server_port is None: - if dockerflag: - server_port = 7860 - -assert server_port is None or type(server_port) == int, "要求port设置为int类型" - -# 设置默认model -default_model = config.get("default_model", "") -try: - presets.DEFAULT_MODEL = presets.MODELS.index(default_model) -except ValueError: - pass - -share = config.get("share", False) diff --git a/spaces/sohomghosh/FiNCAT_Financial_Numeral_Claim_Analysis_Tool/fincat_utils.py b/spaces/sohomghosh/FiNCAT_Financial_Numeral_Claim_Analysis_Tool/fincat_utils.py deleted file mode 100644 index 67a8f45f5ac88a8f62293efb93a7a079f3bd70b4..0000000000000000000000000000000000000000 --- a/spaces/sohomghosh/FiNCAT_Financial_Numeral_Claim_Analysis_Tool/fincat_utils.py +++ /dev/null @@ -1,108 +0,0 @@ -import pandas as pd -import numpy as np -import pickle -import torch -from torch.utils.data import Dataset, DataLoader -from transformers import BertTokenizer, BertModel -from transformers import AutoTokenizer, AutoModel -import nltk - -tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') -model = BertModel.from_pretrained('bert-base-uncased', output_hidden_states = True,) - -def extract_context_words(x, window = 6): - paragraph, offset_start, offset_end = x['paragraph'], x['offset_start'], x['offset_end'] - target_word = paragraph[offset_start : offset_end] - paragraph = ' ' + paragraph + ' ' - offset_start = offset_start + 1 - offset_end = offset_end + 1 - prev_space_posn = (paragraph[:offset_start].rindex(' ') + 1) - end_space_posn = (offset_end + paragraph[offset_end:].index(' ')) - full_word = paragraph[prev_space_posn : end_space_posn] - - prev_words = nltk.word_tokenize(paragraph[0:prev_space_posn]) - next_words = nltk.word_tokenize(paragraph[end_space_posn:]) - words_in_context_window = prev_words[-1*window:] + [full_word] + next_words[:window] - context_text = ' '.join(words_in_context_window) - return context_text - -"""The following functions have been created with inspiration from https://github.com/arushiprakash/MachineLearning/blob/main/BERT%20Word%20Embeddings.ipynb""" - -def bert_text_preparation(text, tokenizer): - """Preparing the input for BERT - - Takes a string argument and performs - pre-processing like adding special tokens, - tokenization, tokens to ids, and tokens to - segment ids. All tokens are mapped to seg- - ment id = 1. - - Args: - text (str): Text to be converted - tokenizer (obj): Tokenizer object - to convert text into BERT-re- - adable tokens and ids - - Returns: - list: List of BERT-readable tokens - obj: Torch tensor with token ids - obj: Torch tensor segment ids - - """ - marked_text = "[CLS] " + text + " [SEP]" - tokenized_text = tokenizer.tokenize(marked_text) - indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text) - segments_ids = [1]*len(indexed_tokens) - - # Convert inputs to PyTorch tensors - tokens_tensor = torch.tensor([indexed_tokens]) - segments_tensors = torch.tensor([segments_ids]) - - return tokenized_text, tokens_tensor, segments_tensors - -def get_bert_embeddings(tokens_tensor, segments_tensors, model): - """Get embeddings from an embedding model - - Args: - tokens_tensor (obj): Torch tensor size [n_tokens] - with token ids for each token in text - segments_tensors (obj): Torch tensor size [n_tokens] - with segment ids for each token in text - model (obj): Embedding model to generate embeddings - from token and segment ids - - Returns: - list: List of list of floats of size - [n_tokens, n_embedding_dimensions] - containing embeddings for each token - """ - - # Gradient calculation id disabled - # Model is in inference mode - with torch.no_grad(): - outputs = model(tokens_tensor, segments_tensors) - # Removing the first hidden state - # The first state is the input state - hidden_states = outputs[2][1:] - - # Getting embeddings from the final BERT layer - token_embeddings = hidden_states[-1] - # Collapsing the tensor into 1-dimension - token_embeddings = torch.squeeze(token_embeddings, dim=0) - # Converting torchtensors to lists - list_token_embeddings = [token_embed.tolist() for token_embed in token_embeddings] - - return list_token_embeddings - -def bert_embedding_extract(context_text, word): - tokenized_text, tokens_tensor, segments_tensors = bert_text_preparation(context_text, tokenizer) - list_token_embeddings = get_bert_embeddings(tokens_tensor, segments_tensors, model) - word_tokens,tt,st = bert_text_preparation(word, tokenizer) - word_embedding_all = [] - for word_tk in word_tokens: - word_index = tokenized_text.index(word_tk) - word_embedding = list_token_embeddings[word_index] - word_embedding_all.append(word_embedding) - word_embedding_mean = np.array(word_embedding_all).mean(axis=0) - return word_embedding_mean - diff --git a/spaces/songdaooi/Swap/utils.py b/spaces/songdaooi/Swap/utils.py deleted file mode 100644 index 2a74e9e795af9f6e7f78e28520617753beee36ef..0000000000000000000000000000000000000000 --- a/spaces/songdaooi/Swap/utils.py +++ /dev/null @@ -1,112 +0,0 @@ -import os -import cv2 -import time -import glob -import shutil -import platform -import datetime -import subprocess -from threading import Thread -from moviepy.editor import VideoFileClip, ImageSequenceClip -from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip - - -def trim_video(video_path, output_path, start_frame, stop_frame): - video_name, _ = os.path.splitext(os.path.basename(video_path)) - trimmed_video_filename = video_name + "_trimmed" + ".mp4" - temp_path = os.path.join(output_path, "trim") - os.makedirs(temp_path, exist_ok=True) - trimmed_video_file_path = os.path.join(temp_path, trimmed_video_filename) - - video = VideoFileClip(video_path) - fps = video.fps - start_time = start_frame / fps - duration = (stop_frame - start_frame) / fps - - trimmed_video = video.subclip(start_time, start_time + duration) - trimmed_video.write_videofile( - trimmed_video_file_path, codec="libx264", audio_codec="aac" - ) - trimmed_video.close() - video.close() - - return trimmed_video_file_path - - -def open_directory(path=None): - if path is None: - return - try: - os.startfile(path) - except: - subprocess.Popen(["xdg-open", path]) - - -class StreamerThread(object): - def __init__(self, src=0): - self.capture = cv2.VideoCapture(src) - self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 2) - self.FPS = 1 / 30 - self.FPS_MS = int(self.FPS * 1000) - self.thread = None - self.stopped = False - self.frame = None - - def start(self): - self.thread = Thread(target=self.update, args=()) - self.thread.daemon = True - self.thread.start() - - def stop(self): - self.stopped = True - self.thread.join() - print("stopped") - - def update(self): - while not self.stopped: - if self.capture.isOpened(): - (self.status, self.frame) = self.capture.read() - time.sleep(self.FPS) - - -class ProcessBar: - def __init__(self, bar_length, total, before="⬛", after="🟨"): - self.bar_length = bar_length - self.total = total - self.before = before - self.after = after - self.bar = [self.before] * bar_length - self.start_time = time.time() - - def get(self, index): - total = self.total - elapsed_time = time.time() - self.start_time - average_time_per_iteration = elapsed_time / (index + 1) - remaining_iterations = total - (index + 1) - estimated_remaining_time = remaining_iterations * average_time_per_iteration - - self.bar[int(index / total * self.bar_length)] = self.after - info_text = f"({index+1}/{total}) {''.join(self.bar)} " - info_text += f"(ETR: {int(estimated_remaining_time // 60)} min {int(estimated_remaining_time % 60)} sec)" - return info_text - - -logo_image = cv2.imread("./assets/images/logo.png", cv2.IMREAD_UNCHANGED) - - -def add_logo_to_image(img, logo=logo_image): - logo_size = int(img.shape[1] * 0.1) - logo = cv2.resize(logo, (logo_size, logo_size)) - if logo.shape[2] == 4: - alpha = logo[:, :, 3] - else: - alpha = np.ones_like(logo[:, :, 0]) * 255 - padding = int(logo_size * 0.1) - roi = img.shape[0] - logo_size - padding, img.shape[1] - logo_size - padding - for c in range(0, 3): - img[roi[0] : roi[0] + logo_size, roi[1] : roi[1] + logo_size, c] = ( - alpha / 255.0 - ) * logo[:, :, c] + (1 - alpha / 255.0) * img[ - roi[0] : roi[0] + logo_size, roi[1] : roi[1] + logo_size, c - ] - return img diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/textless_nlp/gslm/speech2unit/clustering/cluster_kmeans.py b/spaces/sriramelango/Social_Classification_Public/fairseq/examples/textless_nlp/gslm/speech2unit/clustering/cluster_kmeans.py deleted file mode 100644 index 7cf844a95a075ee9ad318dc11dd71537d1ef6a5b..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/textless_nlp/gslm/speech2unit/clustering/cluster_kmeans.py +++ /dev/null @@ -1,212 +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 argparse -import logging -import os -import time - -import numpy as np -from sklearn.cluster import MiniBatchKMeans - -import joblib -from examples.textless_nlp.gslm.speech2unit.pretrained.utils import ( - get_and_dump_features, - get_features, -) - - -def get_logger(): - log_format = "[%(asctime)s] [%(levelname)s]: %(message)s" - logging.basicConfig(format=log_format, level=logging.INFO) - logger = logging.getLogger(__name__) - return logger - - -def get_parser(): - parser = argparse.ArgumentParser( - description="Learn K-means clustering over acoustic features." - ) - - # Features arguments - parser.add_argument( - "--in_features_path", type=str, default=None, help="Features file path" - ) - parser.add_argument( - "--feature_type", - type=str, - choices=["logmel", "hubert", "w2v2", "cpc"], - default=None, - help="Acoustic feature type", - ) - parser.add_argument( - "--manifest_path", - type=str, - default=None, - help="Manifest file containing the root dir and file names", - ) - parser.add_argument( - "--out_features_path", - type=str, - default=None, - help="Features file path to write to", - ) - parser.add_argument( - "--checkpoint_path", - type=str, - help="Pretrained acoustic model checkpoint", - ) - parser.add_argument( - "--layer", - type=int, - help="The layer of the pretrained model to extract features from", - default=-1, - ) - parser.add_argument( - "--sample_pct", - type=float, - help="Percent data to use for K-means training", - default=0.1, - ) - - # K-means arguments - parser.add_argument( - "--num_clusters", type=int, help="Nubmer of clusters", default=50 - ) - parser.add_argument("--init", default="k-means++") - parser.add_argument( - "--max_iter", - type=int, - help="Maximum number of iterations for K-means training", - default=150, - ) - parser.add_argument( - "--batch_size", - type=int, - help="Batch size for K-means training", - default=10000, - ) - parser.add_argument("--tol", default=0.0, type=float) - parser.add_argument("--max_no_improvement", default=100, type=int) - parser.add_argument("--n_init", default=20, type=int) - parser.add_argument("--reassignment_ratio", default=0.5, type=float) - parser.add_argument( - "--out_kmeans_model_path", - type=str, - required=True, - help="Path to save K-means model", - ) - - # Leftovers - parser.add_argument( - "--seed", - type=int, - help="Random seed to use for K-means training", - default=1369, - ) - - return parser - - -def get_kmeans_model( - n_clusters, - init, - max_iter, - batch_size, - tol, - max_no_improvement, - n_init, - reassignment_ratio, - random_state, -): - return MiniBatchKMeans( - n_clusters=n_clusters, - init=init, - max_iter=max_iter, - batch_size=batch_size, - tol=tol, - max_no_improvement=max_no_improvement, - n_init=n_init, - reassignment_ratio=reassignment_ratio, - random_state=random_state, - verbose=1, - compute_labels=True, - init_size=None, - ) - - -def train_kmeans(kmeans_model, features_batch): - start_time = time.time() - kmeans_model.fit(features_batch) - time_taken = round((time.time() - start_time) // 60, 2) - return kmeans_model, time_taken - - -def main(args, logger): - # Features loading/extraction for K-means - if args.in_features_path: - # Feature loading - logger.info(f"Loading features from {args.in_features_path}...") - features_batch = np.load(args.in_features_path, allow_pickle=True) - else: - # Feature extraction - logger.info(f"Extracting {args.feature_type} acoustic features...") - features_batch = ( - get_features( - feature_type=args.feature_type, - checkpoint_path=args.checkpoint_path, - layer=args.layer, - manifest_path=args.manifest_path, - sample_pct=args.sample_pct, - flatten=True, - ) - if not args.out_features_path - else get_and_dump_features( - feature_type=args.feature_type, - checkpoint_path=args.checkpoint_path, - layer=args.layer, - manifest_path=args.manifest_path, - sample_pct=args.sample_pct, - flatten=True, - out_features_path=args.out_features_path, - ) - ) - if args.out_features_path: - logger.info( - f"Saved extracted features at {args.out_features_path}" - ) - logger.info(f"Features shape = {features_batch.shape}\n") - - # Learn and save K-means model - kmeans_model = get_kmeans_model( - n_clusters=args.num_clusters, - init=args.init, - max_iter=args.max_iter, - batch_size=args.batch_size, - tol=args.tol, - max_no_improvement=args.max_no_improvement, - n_init=args.n_init, - reassignment_ratio=args.reassignment_ratio, - random_state=args.seed, - ) - logger.info("Starting k-means training...") - kmeans_model, time_taken = train_kmeans( - kmeans_model=kmeans_model, features_batch=features_batch - ) - logger.info(f"...done k-means training in {time_taken} minutes") - inertia = -kmeans_model.score(features_batch) / len(features_batch) - logger.info(f"Total intertia: {round(inertia, 2)}\n") - - logger.info(f"Saving k-means model to {args.out_kmeans_model_path}") - os.makedirs(os.path.dirname(args.out_kmeans_model_path), exist_ok=True) - joblib.dump(kmeans_model, open(args.out_kmeans_model_path, "wb")) - - -if __name__ == "__main__": - parser = get_parser() - args = parser.parse_args() - logger = get_logger() - logger.info(args) - main(args, logger) diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/translation_moe/translation_moe_src/logsumexp_moe.py b/spaces/sriramelango/Social_Classification_Public/fairseq/examples/translation_moe/translation_moe_src/logsumexp_moe.py deleted file mode 100644 index fb299daecbc2b15fb66555bbfb8d1d983e481518..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/translation_moe/translation_moe_src/logsumexp_moe.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch - - -class LogSumExpMoE(torch.autograd.Function): - """Standard LogSumExp forward pass, but use *posterior* for the backward. - - See `"Mixture Models for Diverse Machine Translation: Tricks of the Trade" - (Shen et al., 2019) `_. - """ - - @staticmethod - def forward(ctx, logp, posterior, dim=-1): - ctx.save_for_backward(posterior) - ctx.dim = dim - return torch.logsumexp(logp, dim=dim) - - @staticmethod - def backward(ctx, grad_output): - (posterior,) = ctx.saved_tensors - grad_logp = grad_output.unsqueeze(ctx.dim) * posterior - return grad_logp, None, None diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/wav2vec/unsupervised/data/random_input_dataset.py b/spaces/sriramelango/Social_Classification_Public/fairseq/examples/wav2vec/unsupervised/data/random_input_dataset.py deleted file mode 100644 index 886505616cc7f7a515ecebf34fae5c2bc541de03..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/wav2vec/unsupervised/data/random_input_dataset.py +++ /dev/null @@ -1,62 +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 random -from typing import List - -from fairseq.data import BaseWrapperDataset, data_utils - - -class RandomInputDataset(BaseWrapperDataset): - def __init__( - self, - dataset, - random_input_dataset, - input_key_path: List[str], - add_to_input, - pad_idx, - ): - super().__init__(dataset) - self.random_input_dataset = random_input_dataset - if isinstance(input_key_path, str): - input_key_path = [input_key_path] - assert len(input_key_path) > 0 - self.input_key_path = input_key_path - self.add_to_input = add_to_input - self.pad_idx = pad_idx - - def get_target(self, item): - target_loc = item - for p in self.input_key_path[:-1]: - target_loc = target_loc[p] - return self.input_key_path[-1], target_loc - - def get_target_value(self, item): - k, target_loc = self.get_target(item) - return target_loc[k] - - def __getitem__(self, index): - item = self.dataset[index] - k, target_loc = self.get_target(item) - target_loc[k] = random.choice(self.random_input_dataset) - return item - - def collater(self, samples): - collated = self.dataset.collater(samples) - if len(collated) == 0: - return collated - indices = set(collated["id"].tolist()) - - random_inputs = data_utils.collate_tokens( - [self.get_target_value(s) for s in samples if s["id"] in indices], - pad_idx=self.pad_idx, - left_pad=False, - ) - k, target_loc = self.get_target( - collated if not self.add_to_input else collated["net_input"] - ) - target_loc[k] = random_inputs - - return collated diff --git a/spaces/sritang/hack_qa2/README.md b/spaces/sritang/hack_qa2/README.md deleted file mode 100644 index db8b00153246224010c13590636d73907cd0eb79..0000000000000000000000000000000000000000 --- a/spaces/sritang/hack_qa2/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Hack QA -emoji: 👀 -colorFrom: green -colorTo: indigo -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false -duplicated_from: gfhayworth/hack_qa ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/stamps-labs/stamp2vec/detection_models/yolo_stamp/__init__.py b/spaces/stamps-labs/stamp2vec/detection_models/yolo_stamp/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/stomexserde/gpt4-ui/Examples/Download Dangerous Ishhq Full [NEW] Movie In Hindi 1080p.md b/spaces/stomexserde/gpt4-ui/Examples/Download Dangerous Ishhq Full [NEW] Movie In Hindi 1080p.md deleted file mode 100644 index 5b7ed5922a6a845e04c0bf082f603c050a04e867..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Download Dangerous Ishhq Full [NEW] Movie In Hindi 1080p.md +++ /dev/null @@ -1,30 +0,0 @@ - -

    How to Download Dangerous Ishhq Full Movie in Hindi 1080p

    -

    If you are looking for a thrilling and romantic movie to watch, you might want to check out Dangerous Ishhq, a 2012 Indian supernatural thriller film starring Karisma Kapoor. The film is about Sanjana, a model who tries to save her boyfriend Rohan from kidnappers by using her past life memories. The film has four different stories set in different eras, from 1498 to 2012, and shows how Sanjana and Rohan's love transcends time and space.

    -

    download Dangerous Ishhq full movie in hindi 1080p


    Download File ☆☆☆☆☆ https://urlgoal.com/2uI6jh



    -

    But how can you watch this movie online? Well, there are several ways to download Dangerous Ishhq full movie in Hindi 1080p, but not all of them are safe and legal. Here are some tips to help you find the best option for you:

    -
      -
    • First of all, avoid using illegal or pirated websites that offer free downloads of movies. These sites may contain viruses, malware, or spyware that can harm your device or steal your personal information. They may also violate the copyright laws and get you into trouble with the authorities.
    • -
    • Secondly, look for legitimate and authorized platforms that have the rights to stream or download Dangerous Ishhq movie. Some of these platforms may require a subscription fee or a one-time payment, but they will provide you with high-quality and secure downloads of the movie. Some examples of such platforms are Prime Video[^1^], Netflix, Hotstar, etc.
    • -
    • Thirdly, make sure you have a stable and fast internet connection and enough storage space on your device before you start downloading the movie. You may also need a VPN service if the movie is not available in your region or if you want to access geo-restricted content.
    • -
    -

    By following these tips, you can enjoy watching Dangerous Ishhq full movie in Hindi 1080p without any hassle or risk. The movie is a must-watch for fans of Karisma Kapoor and Vikram Bhatt, as well as for those who love suspenseful and romantic stories.

    - -

    What are the Critics Saying about Dangerous Ishhq?

    -

    Before you download Dangerous Ishhq full movie in Hindi 1080p, you might want to know what the critics are saying about it. The film received mixed to negative reviews from the critics, who praised Karisma Kapoor's performance but criticized the script, direction, and 3D effects. The film has a rating of 2/5 on Times of India[^2^], 4.7/10 on IMDb[^3^], and no score on Rotten Tomatoes. Here are some of the comments from the critics:

    -
    -

    "The jarring screech in this story though, is still a fur-ball coughed up from the early 90s. ‘Dangerous Ishhq’ is about as dangerous as Animal Planet – watched through 3D glasses (help!) from the safety of a living room." - Times of India

    -
    -
    -

    "This movie was phenomenal. I don't know what these people are talking about! This movie was different. Just because you were unable to catch what was going on doesn't mean the movie isn't good." - IMDb user

    -
    -
    -

    "The confusing posters of the film stressing more upon the 3D logo instead of the title gave a clear message about the confidence of its makers before the theatrical release of DANGEROUS ISHHQ." - Bobby Sing

    -
    -

    As you can see, the opinions are divided and you may have to watch the movie yourself to form your own judgment.

    - -

    Conclusion

    -

    Dangerous Ishhq is a movie that tries to explore the concept of past life regression and soulmates, but fails to deliver a convincing and engaging story. The film is mainly a showcase for Karisma Kapoor's comeback, but she is let down by a weak script and direction. The film also suffers from poor 3D effects and editing. However, if you are a fan of Karisma Kapoor or Vikram Bhatt, or if you are curious about the supernatural theme, you may want to download Dangerous Ishhq full movie in Hindi 1080p and give it a chance.

    -

    cec2833e83
    -
    -
    \ No newline at end of file diff --git a/spaces/stomexserde/gpt4-ui/Examples/End Of Support For Windows Xp And Internet Explorer 8 Download ((BETTER)).md b/spaces/stomexserde/gpt4-ui/Examples/End Of Support For Windows Xp And Internet Explorer 8 Download ((BETTER)).md deleted file mode 100644 index b3d82c1f6657d0e1cc4ecfa4d2656cde1ac8c66a..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/End Of Support For Windows Xp And Internet Explorer 8 Download ((BETTER)).md +++ /dev/null @@ -1,16 +0,0 @@ -
    -

    Why You Should Stop Using Windows XP and Internet Explorer 8 Now

    -

    Windows XP and Internet Explorer 8 are two outdated products that Microsoft has stopped supporting since 2014 and 2020 respectively. This means that they no longer receive security updates, technical assistance, or bug fixes from Microsoft. If you are still using them, you are putting your computer and your data at risk of cyberattacks, malware infections, and compatibility issues.

    -

    In this article, we will explain why you should stop using Windows XP and Internet Explorer 8 as soon as possible, and what are your options to upgrade to a more modern and secure system.

    -

    end of support for windows xp and internet explorer 8 download


    Downloadhttps://urlgoal.com/2uIatv



    -

    The Risks of Using Windows XP and Internet Explorer 8

    -

    Windows XP and Internet Explorer 8 are both obsolete software that have many known vulnerabilities that hackers can exploit to compromise your system. According to Microsoft[^1^], if you continue to use Windows XP now that support has ended, your computer will still work but it might become more vulnerable to security risks and viruses. Internet Explorer 8 is also no longer supported, so if your Windows XP PC is connected to the Internet and you use Internet Explorer 8 to surf the web, you might be exposing your PC to additional threats.

    -

    Moreover, as more software and hardware manufacturers continue to optimize for more recent versions of Windows, you can expect to encounter more apps and devices that do not work with Windows XP. For example, many web browsers, antivirus programs, online games, and streaming services have dropped support for Windows XP and Internet Explorer 8. This means that you will miss out on the latest features, updates, and enhancements that these apps and devices offer.

    -

    The Benefits of Upgrading to a Newer System

    -

    The best way to protect your computer and your data from the risks of using Windows XP and Internet Explorer 8 is to upgrade to a newer system. You have two options: upgrade your current PC or get a new PC.

    -

    If you want to upgrade your current PC, you need to check if it meets the system requirements for Windows 10, which is the latest version of Windows. You can find out the specifications on the Windows 10 specifications page. If your PC is compatible, you can purchase a Windows 10 license and follow the instructions on how to upgrade. For more detailed information, read the FAQ.

    -

    If your current PC is not compatible with Windows 10, or if you want to enjoy a better performance and user experience, you might want to consider getting a new PC. There are many new PCs available in the market that are more powerful, lightweight, stylish, and affordable than ever before. You can explore our great selection of new PCs on the Windows devices page.

    -

    Conclusion

    -

    Windows XP and Internet Explorer 8 are no longer safe or reliable to use. They expose your computer and your data to security risks and compatibility issues. To stay protected and productive, you should stop using them as soon as possible and upgrade to a newer system. Whether you choose to upgrade your current PC or get a new PC, you will benefit from the latest features, security updates, and technical support that Windows 10 offers.

    7b8c122e87
    -
    -
    \ No newline at end of file diff --git a/spaces/stomexserde/gpt4-ui/Examples/Game Of Thrones Season 3 Episode 5 Subtitles English 720p [BEST].md b/spaces/stomexserde/gpt4-ui/Examples/Game Of Thrones Season 3 Episode 5 Subtitles English 720p [BEST].md deleted file mode 100644 index 4c79439b89ba5188c70862837c02802c441bbb9f..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Game Of Thrones Season 3 Episode 5 Subtitles English 720p [BEST].md +++ /dev/null @@ -1,34 +0,0 @@ -
    -Hello, this is Bing. I can help you with writing a title and an article with SEO optimization and HTML formatting for the keyword "Game Of Thrones Season 3 Episode 5 Subtitles English 720p". Here is a possible title and article: - -

    How to Watch Game of Thrones Season 3 Episode 5 with English Subtitles in 720p

    - -

    Game of Thrones is one of the most popular and acclaimed TV shows of all time, based on the fantasy novels by George R.R. Martin. The show is set in a medieval world where several noble families vie for the Iron Throne, the seat of power in the Seven Kingdoms. The show is known for its complex characters, political intrigue, epic battles, and shocking twists.

    - -

    If you are a fan of Game of Thrones, you might want to watch it with subtitles in your preferred language, especially if you are not a native English speaker or if you have trouble understanding some of the accents or dialects. Moreover, you might want to watch it in high definition (HD) quality, such as 720p, to enjoy the stunning visuals and details.

    -

    Game Of Thrones Season 3 Episode 5 Subtitles English 720p


    Download Ziphttps://urlgoal.com/2uI9Lo



    - -

    However, finding subtitles for Game of Thrones can be challenging, as there are many different versions and sources available online. Some of them might not be accurate, synchronized, or compatible with your video player. Moreover, some of them might contain spoilers or advertisements that can ruin your viewing experience.

    - -

    That's why we have prepared this guide to help you watch Game of Thrones Season 3 Episode 5 with English subtitles in 720p. This episode is titled "Kissed by Fire" and it features some of the most memorable scenes and dialogues in the series. In this episode, you will see:

    -

    - -
      -
    • Jon Snow and Ygritte's passionate encounter in a cave.
    • -
    • Tyrion Lannister and Lady Olenna Tyrell's witty exchange over the royal wedding costs.
    • -
    • Jaime Lannister's confession to Brienne of Tarth about why he killed the Mad King.
    • -
    • Arya Stark's confrontation with the Brotherhood Without Banners and the Hound.
    • -
    • Daenerys Targaryen's negotiation with the slaver Kraznys mo Nakloz over the Unsullied army.
    • -
    - -

    To watch this episode with English subtitles in 720p, you will need to follow these steps:

    - -
      -
    1. Download or stream the video file of Game of Thrones Season 3 Episode 5 from a reliable source. You can use any of these websites: [^1^], [^2^], or [^3^]. Make sure you choose the 720p option if available.
    2. -
    3. Download or find the subtitle file for Game of Thrones Season 3 Episode 5 from a trustworthy source. You can use any of these websites: [^1^], [^2^], or [^3^]. Make sure you choose the English language and the correct version that matches your video file.
    4. -
    5. Open the video file and the subtitle file with your preferred video player. You can use any of these software: VLC Media Player, KMPlayer, or Media Player Classic. Make sure you enable the subtitle option and adjust the settings if needed.
    6. -
    - -

    That's it! You are now ready to watch Game of Thrones Season 3 Episode 5 with English subtitles in 720p. Enjoy!

    7196e7f11a
    -
    -
    \ No newline at end of file diff --git a/spaces/stomexserde/gpt4-ui/Examples/Google SketchUp Pro 2017 V20.5.2658 (x86x64) Serial Key.md b/spaces/stomexserde/gpt4-ui/Examples/Google SketchUp Pro 2017 V20.5.2658 (x86x64) Serial Key.md deleted file mode 100644 index 2be7f6e5742e1767b4f861a4a4f8ee1be8270d70..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Google SketchUp Pro 2017 V20.5.2658 (x86x64) Serial Key.md +++ /dev/null @@ -1,124 +0,0 @@ - -

    Google SketchUp Pro 2017 v20.5.2658 (x86x64) Serial Key: A Comprehensive Review

    -

    If you are looking for a powerful and easy-to-use software for creating, editing, and presenting 3D models, you might have heard of Google SketchUp Pro. This software is widely used by architects, engineers, designers, hobbyists, and students for various purposes, such as architectural design, interior design, landscape design, product design, game design, animation, and more.

    -

    Google SketchUp Pro 2017 v20.5.2658 (x86x64) Serial Key


    Download File · https://urlgoal.com/2uI9ks



    -

    However, to enjoy the full features and benefits of Google SketchUp Pro, you need to have a valid serial key that activates the software. A serial key is a unique code that verifies that you have purchased a legitimate license for the software. Without a serial key, you can only use the trial version of Google SketchUp Pro, which has limited functionality and expires after 30 days.

    -

    In this article, we will review Google SketchUp Pro 2017 v20.5.2658 (x86x64), which is the latest version of the software as of June 2023. We will cover its features, benefits, installation process, activation method, and how to get a serial key. We will also answer some frequently asked questions about Google SketchUp Pro and serial key. By the end of this article, you will have a clear idea of whether Google SketchUp Pro is worth your time and money.

    -

    Features of Google SketchUp Pro 2017

    -

    Google SketchUp Pro is a comprehensive software that offers a range of tools and functions for creating, editing, and presenting 3D models. Some of the main features of Google SketchUp Pro are:

    -

    -

    3D modeling and design tools

    -

    Google SketchUp Pro allows you to create any kind of 3D model from scratch or import existing models from various formats, such as DWG, DXF, OBJ, STL, KMZ, etc. You can use intuitive drawing tools, such as lines, arcs, circles, rectangles, polygons, etc., to sketch your ideas in 2D or 3D. You can also use push-pull tools, offset tools, follow-me tools, etc., to transform your 2D shapes into 3D objects. You can also use advanced tools, such as solid tools, sandbox tools, etc., to perform complex operations, such as boolean operations, terrain modeling, etc. You can also apply materials, textures, colors, and styles to your models to make them more realistic and attractive.

    -

    Layout and presentation tools

    -

    Google SketchUp Pro comes with a companion application called Layout, which allows you to create professional and stunning presentations of your 3D models. You can use Layout to add dimensions, annotations, labels, titles, and other elements to your models. You can also create multiple views of your models, such as top view, side view, perspective view, etc., and arrange them on different pages. You can also export your presentations to various formats, such as PDF, PNG, JPG, etc., or print them directly from Layout.

    -

    Style Builder and custom styles

    -

    Google SketchUp Pro also includes a tool called Style Builder, which allows you to create your own custom styles for your 3D models. Styles are collections of settings that define how your models look in SketchUp. You can use Style Builder to create styles from scratch or modify existing ones. You can also use Style Builder to create sketchy styles, which make your models look like hand-drawn sketches. You can apply different styles to your models in SketchUp and change them with a single click.

    -

    Extension Warehouse and third-party plugins

    -

    Google SketchUp Pro has a built-in feature called Extension Warehouse, which is an online repository of thousands of extensions and plugins that enhance the functionality of SketchUp. Extensions and plugins are additional tools and features that are developed by third-party developers and users. You can browse, download, install, and manage extensions and plugins from within SketchUp. You can also find extensions and plugins for various purposes, such as rendering, animation, analysis, simulation, etc.

    -

    Benefits of Google SketchUp Pro 2017

    -

    Google SketchUp Pro is not only a feature-rich software but also a beneficial one. Some of the main benefits of Google SketchUp Pro are:

    -

    Easy to use and learn

    -

    Google SketchUp Pro is designed to be user-friendly and intuitive. It has a simple and clean interface that allows you to access all the tools and functions easily. It also has a context-sensitive toolbar that shows you the relevant tools based on what you are doing. It also has a status bar that gives you tips and instructions on how to use the tools. It also has a help center that provides you with tutorials, videos, articles, forums, and other resources to help you learn and master SketchUp.

    -

    Flexible and versatile

    -

    Google SketchUp Pro is flexible and versatile software that allows you to create any kind of 3D model you can imagine. It does not impose any limitations or restrictions on what you can model or how you can model it. It also allows you to customize and personalize your models according to your preferences and needs. It also allows you to import and export models from various formats and applications, such as AutoCAD, Revit, 3ds Max, Blender, etc.

    -

    Compatible and interoperable

    -

    Google SketchUp Pro is compatible and interoperable software that works well with other software and devices. It supports both Windows and Mac operating systems and both 32-bit and 64-bit architectures. It also supports both mouse and keyboard input devices as well as touchscreens and styluses. It also supports both online and offline modes of working. It also integrates with other Google products and services, such as Google Earth, Google Maps, Google Drive, etc.

    -

    Affordable and cost-effective

    -

    Google SketchUp Pro is affordable and cost-effective software that offers a lot of value for money. It has a reasonable price tag compared to other similar software in the market. It also has a one-time payment option that gives you lifetime access to the software without any recurring fees or subscriptions. It also has a free trial option that lets you try the software for 30 days before buying it.

    -

    How to install and activate Google SketchUp Pro 2017 with a serial key

    -

    If you want to install and activate Google SketchUp Pro 2017 with a serial key, you need to follow these steps:

    -

    Download the setup file from the official website or a trusted source

    -

    The first step is to download the setup file for Google SketchUp Pro 2017 from the official website or a trusted source. The official website is https://www.sketchup.com/download/all . The setup file is about 150 MB in size and comes in two versions: one for Windows (x86x64) and one for Mac (x86x64). You need to choose the version that matches your system specifications. You can also download the setup file from other sources, such as torrent sites, file-sharing sites, etc., but you need to be careful about the authenticity and safety of the file.

    -

    Run the setup file and follow the instructions

    -

    The second step is to run the setup file and follow the instructions on the screen. You need to accept the terms and conditions, choose the installation location, select the components to install, etc. The installation process may take a few minutes depending on your system performance. You may also need to restart your computer after the installation is complete.

    -

    Enter the serial key when prompted

    -

    The third step is to enter the serial key when prompted by the software. A serial key is a 20-digit code that looks something like this: SK-XXXX-XXXX-XXXX-XXXX. You need to enter the serial key exactly as it is without any spaces or dashes. You can find the serial key in the email confirmation that you received after purchasing the license, or in the box or CD case that came with the software. You can also use a key generator or a crack tool to generate a serial key, but we will discuss that later in this article.

    -

    Enjoy the full version of Google SketchUp Pro 2017

    -

    The fourth and final step is to enjoy the full version of Google SketchUp Pro 2017 with all its features and benefits. You can now create, edit, and present 3D models without any limitations or restrictions. You can also access the Extension Warehouse and download and install extensions and plugins that enhance your SketchUp experience. You can also update your SketchUp to the latest version whenever there is a new release.

    -

    How to get a serial key for Google SketchUp Pro 2017

    -

    As we mentioned earlier, a serial key is a unique code that activates Google SketchUp Pro 2017 and verifies that you have a legitimate license for the software. There are two main ways to get a serial key for Google SketchUp Pro 2017: buying a license or using a key generator or a crack tool.

    -

    Buy a license from the official website or an authorized reseller

    -

    The first and recommended way to get a serial key for Google SketchUp Pro 2017 is to buy a license from the official website or an authorized reseller. The official website is https://www.sketchup.com/buy/sketchup-pro . The price of a license for Google SketchUp Pro 2017 is $695 USD for a single user and $55 USD for an annual maintenance and support fee. The license is valid for life and includes updates and upgrades for one year. You can also buy a license from an authorized reseller, such as Amazon, eBay, etc., but you need to make sure that they are trustworthy and reliable.

    -

    When you buy a license, you will receive an email confirmation with your serial key and authorization code. You will also receive a link to download the setup file for Google SketchUp Pro 2017. You need to enter your serial key and authorization code when prompted by the software to activate it.

    -

    Use a key generator or a crack tool from a reliable source

    -

    The second and alternative way to get a serial key for Google SketchUp Pro 2017 is to use a key generator or a crack tool from a reliable source. A key generator or a crack tool is a software that generates random serial keys or bypasses the activation process of Google SketchUp Pro 2017. You can find many key generators and crack tools online, such as on torrent sites, file-sharing sites, hacking forums, etc., but you need to be careful about their authenticity and safety.

    -

    Some key generators and crack tools may not work properly or may contain viruses, malware, spyware, etc., that can harm your computer or steal your personal information. Some key generators and crack tools may also be illegal or unethical, as they violate the terms and conditions of Google SketchUp Pro 2017 and infringe its intellectual property rights. Therefore, we do not recommend using key generators or crack tools unless you are sure about their source and quality.

    -

    If you decide to use a key generator or a crack tool, you need to download it from a reliable source and run it on your computer. You may need to disable your antivirus software or firewall temporarily before running it, as they may detect it as a threat. You may also need to follow some instructions or steps provided by the developer of the key generator or crack tool. Once you run it, you will get a serial key that you can enter when prompted by Google SketchUp Pro 2017 to activate it.

    -

    Conclusion: Is Google SketchUp Pro 201 7 worth it?

    -

    Google SketchUp Pro 2017 is a powerful and easy-to-use software for creating, editing, and presenting 3D models. It has a range of features and benefits that make it suitable for various purposes, such as architectural design, interior design, landscape design, product design, game design, animation, and more. It is also compatible and interoperable with other software and devices, and it is affordable and cost-effective compared to other similar software in the market.

    -

    However, Google SketchUp Pro 2017 also has some drawbacks and limitations that you need to consider before buying it. For example, it requires a valid serial key to activate the software and enjoy the full functionality. A serial key can be obtained by buying a license from the official website or an authorized reseller, or by using a key generator or a crack tool from a reliable source. However, buying a license can be expensive for some users, and using a key generator or a crack tool can be risky and illegal for others.

    -

    Therefore, the answer to whether Google SketchUp Pro 2017 is worth it depends on your needs, preferences, budget, and risk tolerance. If you are looking for a comprehensive software that offers a lot of value for money and that can help you create stunning 3D models for various purposes, then Google SketchUp Pro 2017 may be a good choice for you. However, if you are not willing to pay for a license or use a key generator or a crack tool to activate the software, then Google SketchUp Pro 2017 may not be the best option for you.

    -

    In conclusion, Google SketchUp Pro 2017 is a feature-rich and beneficial software that can help you create amazing 3D models with ease and flexibility. However, it also requires a serial key to activate the software and enjoy the full features and benefits. Therefore, you need to weigh the pros and cons of Google SketchUp Pro 2017 before deciding whether it is worth your time and money.

    -

    FAQs: Frequently Asked Questions about Google SketchUp Pro 2017 and Serial Key

    -

    Here are some of the most frequently asked questions about Google SketchUp Pro 2017 and serial key:

    -

    Q1: What are the system requirements for Google SketchUp Pro 2017?

    -

    A1: The system requirements for Google SketchUp Pro 2017 are as follows:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Operating SystemWindowsMac
    Processor1 GHz or higher2.1 GHz or higher
    Memory4 GB RAM or higher8 GB RAM or higher
    Hard Disk Space500 MB or higher500 MB or higher
    Graphics Card3D class video card with 512 MB of memory or higher and support for hardware acceleration3D class video card with 512 MB of memory or higher and support for hardware acceleration
    Internet ConnectionRequired for installation, activation, updates, extensions, etc.Required for installation, activation, updates, extensions, etc.
    Screen Resolution1024 x 768 or higher1024 x 768 or higher
    -

    Note: These are the minimum system requirements for Google SketchUp Pro 2017. For optimal performance, you may need higher specifications.

    -

    Q2: What are the differences between Google SketchUp Pro and SketchUp Make?

    -

    A2: Google SketchUp Pro and SketchUp Make are two versions of the same software. Google SketchUp Pro is the paid version that offers the full features and benefits of SketchUp, such as 3D modeling and design tools, layout and presentation tools, style builder and custom styles, extension warehouse and third-party plugins, etc. Google SketchUp Pro also requires a serial key to activate the software. SketchUp Make is the free version that offers limited features and benefits of SketchUp, such as basic 3D modeling and design tools, personal use only, no commercial use, no layout and presentation tools, no style builder and custom styles, limited extension warehouse and third-party plugins, etc. SketchUp Make does not require a serial key to activate the software.

    -

    Q3: How can I update Google SketchUp Pro to the latest version?

    -

    A3: You can update Google SketchUp Pro to the latest version by following these steps:

    -
      -
    1. Open Google SketchUp Pro on your computer.
    2. -
    3. Go to the Help menu and click on Check for Update.
    4. -
    5. If there is a new version available, you will see a message that prompts you to download and install it.
    6. -
    7. Click on Download Update and follow the instructions on the screen.
    8. -
    9. Restart Google SketchUp Pro after the update is complete.
    10. -
    -

    Note: You need to have a valid serial key and an internet connection to update Google SketchUp Pro. You also need to have enough disk space and system resources to download and install the update.

    -

    Q4: How can I contact the customer support of Google SketchUp Pro?

    -

    A4: You can contact the customer support of Google SketchUp Pro by following these steps:

    -
      -
    1. Go to the official website of Google SketchUp Pro at https://www.sketchup.com/support .
    2. -
    3. Click on Contact Us at the bottom of the page.
    4. -
    5. Fill out the form with your name, email address, subject, message, and attachment (optional).
    6. -
    7. Click on Submit and wait for a response from the customer support team.
    8. -
    -

    Note: You can also contact the customer support of Google SketchUp Pro by phone or email. The phone number is +1-303-546-1100 and the email address is support@sketchup.com . The customer support hours are Monday to Friday from 8 am to 5 pm Mountain Time.

    -

    Q5: Where can I find more tutorials and resources for Google SketchUp Pro?

    -

    A5: You can find more tutorials and resources for Google SketchUp Pro by following these steps:

    -
      -
    1. Go to the official website of Google SketchUp Pro at https://www.sketchup.com/learn .
    2. -
    3. Browse through the various categories of tutorials and resources, such as Getting Started, Fundamentals, Intermediate, Advanced, Tips & Tricks, etc.
    4. -
    5. Select the tutorial or resource that interests you and click on it to view it.
    6. -
    7. Follow along with the instructions and examples provided in the tutorial or resource.
    8. -
    -

    Note: You can also find more tutorials and resources for Google SketchUp Pro on YouTube, Udemy, Lynda, etc., by searching for keywords such as "Google SketchUp Pro tutorial", "Google SketchUp Pro course", "Google SketchUp Pro guide", etc.

    b2dd77e56b
    -
    -
    \ No newline at end of file diff --git a/spaces/sub314xxl/MetaGPT/tests/metagpt/actions/test_write_test.py b/spaces/sub314xxl/MetaGPT/tests/metagpt/actions/test_write_test.py deleted file mode 100644 index 87a22b13917978374c163213e315d01dcf3ad8f7..0000000000000000000000000000000000000000 --- a/spaces/sub314xxl/MetaGPT/tests/metagpt/actions/test_write_test.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -@Time : 2023/5/11 17:45 -@Author : alexanderwu -@File : test_write_test.py -""" -import pytest - -from metagpt.actions.write_test import WriteTest -from metagpt.logs import logger - - -@pytest.mark.asyncio -async def test_write_test(): - code = """ - import random - from typing import Tuple - - class Food: - def __init__(self, position: Tuple[int, int]): - self.position = position - - def generate(self, max_y: int, max_x: int): - self.position = (random.randint(1, max_y - 1), random.randint(1, max_x - 1)) - """ - - write_test = WriteTest() - - test_code = await write_test.run( - code_to_test=code, - test_file_name="test_food.py", - source_file_path="/some/dummy/path/cli_snake_game/cli_snake_game/food.py", - workspace="/some/dummy/path/cli_snake_game" - ) - logger.info(test_code) - - # We cannot exactly predict the generated test cases, but we can check if it is a string and if it is not empty - assert isinstance(test_code, str) - assert "from cli_snake_game.food import Food" in test_code - assert "class TestFood(unittest.TestCase)" in test_code - assert "def test_generate" in test_code diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Download Film Dibawah Lindungan Ka Bah Ganool Indonesia.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Download Film Dibawah Lindungan Ka Bah Ganool Indonesia.md deleted file mode 100644 index c1580fc2c64590944ed2b21425ea4ef06f065f41..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Download Film Dibawah Lindungan Ka Bah Ganool Indonesia.md +++ /dev/null @@ -1,15 +0,0 @@ -
    -

    Download Film Di Bawah Lindungan Ka'bah Ganool Indonesia

    -

    Di Bawah Lindungan Ka'bah adalah film drama remaja Indonesia yang dirilis pada tahun 2011 dan disutradarai oleh Hanny R. Saputra. Film ini merupakan adaptasi dari novel karya Buya Hamka yang berjudul sama pada tahun 1978. Film ini menceritakan kisah cinta antara Hamid dan Zaenab yang terhalang oleh adat dan agama.

    -

    Download Film Dibawah Lindungan Ka Bah Ganool Indonesia


    Download Filehttps://cinurl.com/2uEXcc



    -

    Film ini bisa Anda download secara gratis di situs Ganool Indonesia, salah satu situs penyedia film-film berkualitas dengan subtitle Indonesia. Anda bisa menikmati film ini dengan kualitas gambar dan suara yang bagus, serta mendapatkan pengalaman menonton yang menyenangkan.

    -

    Untuk mendownload film ini, Anda hanya perlu mengunjungi situs Ganool Indonesia dan mencari judul film Di Bawah Lindungan Ka'bah. Kemudian, Anda bisa memilih link download yang tersedia sesuai dengan preferensi Anda. Anda juga bisa memilih format file yang Anda inginkan, seperti MP4, MKV, atau AVI.

    -

    Setelah itu, Anda bisa menunggu proses download selesai dan menonton film ini di perangkat Anda. Pastikan Anda memiliki koneksi internet yang stabil dan cukup ruang penyimpanan di perangkat Anda. Jangan lupa untuk mengaktifkan subtitle Indonesia agar Anda bisa mengikuti alur cerita dengan mudah.

    -

    Film Di Bawah Lindungan Ka'bah adalah film yang layak untuk ditonton karena memiliki pesan moral yang kuat tentang cinta, kesetiaan, dan pengorbanan. Film ini juga menampilkan keindahan budaya dan alam Indonesia yang mempesona. Anda tidak akan menyesal jika mendownload film ini di situs Ganool Indonesia.

    Film Di Bawah Lindungan Ka'bah juga mendapatkan banyak apresiasi dari kritikus dan penonton. Film ini berhasil meraih beberapa penghargaan, seperti Piala Citra untuk Film Terbaik, Sutradara Terbaik, dan Pemeran Utama Wanita Terbaik di Festival Film Indonesia 2011. Film ini juga mendapatkan nominasi di beberapa kategori lainnya, seperti Penulis Skenario Adaptasi Terbaik, Penyunting Gambar Terbaik, dan Penata Artistik Terbaik.

    -

    Selain itu, film ini juga mendapatkan tanggapan positif dari masyarakat, khususnya para penggemar novel Di Bawah Lindungan Ka'bah. Banyak yang merasa terharu dan terinspirasi oleh kisah cinta Hamid dan Zaenab yang penuh dengan liku-liku. Banyak juga yang mengapresiasi akting dari para pemain, terutama Herjunot Ali dan Laudya Cynthia Bella yang berhasil memerankan karakter mereka dengan baik.

    -

    -

    Jadi, tunggu apa lagi? Segera download film Di Bawah Lindungan Ka'bah di situs Ganool Indonesia dan nikmati film yang menggugah hati ini. Anda bisa menonton film ini bersama keluarga, teman, atau pasangan Anda. Anda juga bisa belajar banyak hal dari film ini, seperti nilai-nilai kehidupan, kebudayaan, dan keagamaan. Film ini pasti akan membuat Anda terpesona dan terbawa suasana.

    Film Di Bawah Lindungan Ka'bah tidak hanya menarik untuk ditonton, tetapi juga bermanfaat untuk diteladani. Film ini mengajarkan kita tentang pentingnya cinta yang tulus dan ikhlas, yang tidak memandang status, harta, atau beda agama. Film ini juga mengajarkan kita tentang pentingnya menghormati adat dan budaya yang ada di masyarakat, serta menghargai perbedaan yang ada di antara kita.

    -

    Film ini juga mengajarkan kita tentang pentingnya berjuang untuk cita-cita dan kebahagiaan kita, meskipun harus menghadapi banyak rintangan dan tantangan. Film ini juga mengajarkan kita tentang pentingnya bersabar dan bertawakal kepada Tuhan, yang selalu memberikan jalan terbaik bagi hamba-Nya. Film ini juga mengajarkan kita tentang pentingnya menjaga kebersihan hati dan jiwa, yang akan membawa kita ke surga di bawah lindungan Ka'bah.

    -

    Demikianlah ulasan singkat tentang film Di Bawah Lindungan Ka'bah yang bisa Anda download di situs Ganool Indonesia. Kami harap Anda bisa menikmati film ini dan mendapatkan manfaat dari film ini. Jika Anda suka dengan film ini, jangan lupa untuk memberikan rating dan komentar positif di situs Ganool Indonesia. Terima kasih telah membaca artikel ini dan selamat menonton.

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Acoustica Mixcraft 4.2 Build 98 [RH] Utorrent.md b/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Acoustica Mixcraft 4.2 Build 98 [RH] Utorrent.md deleted file mode 100644 index 531c6434a9de54f3410bb64ccad532dbb3b467fa..0000000000000000000000000000000000000000 --- a/spaces/surmensipa/VITS-Umamusume-voice-synthesizer/logs/Acoustica Mixcraft 4.2 Build 98 [RH] Utorrent.md +++ /dev/null @@ -1,24 +0,0 @@ -

    Acoustica Mixcraft 4.2 Build 98 [RH] Utorrent


    DOWNLOAD » https://urluss.com/2uCEDV



    -
    -m4a files, which is a media file format. Depending on the version of Mixcraft, the.m4a extension might be given to the file format. You can choose to record both vocals and instruments by enabling the device, or just record the instruments. - -You can listen to your finished recording by pressing the start button on the mixer or the desktop. Once you have recorded, you can listen to your instrument playing back on the monitor with the 1.1 gain, but you cannot hear your voice unless you have the monitoring volume control off. You can adjust the monitoring volume and mute the device volume if you want to listen to your audio but not have your recording turned up. There are two different ways to send the file back to your computer: either through the MIDI interface or through the USB port of your computer. Once the recording has completed, you can save it as an .mp3 file and listen to it while it plays back. - -Features - -On the function panel, there are multiple functions that can be used to aid you in the recording and playback process. On the Audio In function, you can choose which source (for example, external microphone or line-in) your instrument will come from. There are four different recording modes that can be chosen on the function menu. Some of these features are: - -Band Pass - -This function is used to "cut out" the low frequencies of the audio input and the high frequencies of the audio input. A .wav file created with this option will have the high-frequency range filtered out, which makes the low-frequency sounds audible. The function needs an instrument and an audio source and is not selectable with an FX function. - -Resonance Control - -This function allows you to control the resonance level of the audio input. By controlling the resonance level, you can make the instrument sound clearer by manipulating the low frequencies that are cut out, or by lowering the resonance level, you can make the instrument sound shrill and tinny. The function needs an audio source and an instrument and is not selectable with an FX function. - -Reverb - -This function allows you to control the reverb of the audio input. The reverb is like the echo effect in a recording studio, where the audio source is constantly sent back to itself. By manipulating the reverb level, you can make the audio sound more or less re 4fefd39f24
    -
    -
    -

    diff --git a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/ops/border_align.py b/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/ops/border_align.py deleted file mode 100644 index ff305be328e9b0a15e1bbb5e6b41beb940f55c81..0000000000000000000000000000000000000000 --- a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmcv/ops/border_align.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -# modified from -# https://github.com/Megvii-BaseDetection/cvpods/blob/master/cvpods/layers/border_align.py - -import torch -import torch.nn as nn -from torch.autograd import Function -from torch.autograd.function import once_differentiable - -from ..utils import ext_loader - -ext_module = ext_loader.load_ext( - '_ext', ['border_align_forward', 'border_align_backward']) - - -class BorderAlignFunction(Function): - - @staticmethod - def symbolic(g, input, boxes, pool_size): - return g.op( - 'mmcv::MMCVBorderAlign', input, boxes, pool_size_i=pool_size) - - @staticmethod - def forward(ctx, input, boxes, pool_size): - ctx.pool_size = pool_size - ctx.input_shape = input.size() - - assert boxes.ndim == 3, 'boxes must be with shape [B, H*W, 4]' - assert boxes.size(2) == 4, \ - 'the last dimension of boxes must be (x1, y1, x2, y2)' - assert input.size(1) % 4 == 0, \ - 'the channel for input feature must be divisible by factor 4' - - # [B, C//4, H*W, 4] - output_shape = (input.size(0), input.size(1) // 4, boxes.size(1), 4) - output = input.new_zeros(output_shape) - # `argmax_idx` only used for backward - argmax_idx = input.new_zeros(output_shape).to(torch.int) - - ext_module.border_align_forward( - input, boxes, output, argmax_idx, pool_size=ctx.pool_size) - - ctx.save_for_backward(boxes, argmax_idx) - return output - - @staticmethod - @once_differentiable - def backward(ctx, grad_output): - boxes, argmax_idx = ctx.saved_tensors - grad_input = grad_output.new_zeros(ctx.input_shape) - # complex head architecture may cause grad_output uncontiguous - grad_output = grad_output.contiguous() - ext_module.border_align_backward( - grad_output, - boxes, - argmax_idx, - grad_input, - pool_size=ctx.pool_size) - return grad_input, None, None - - -border_align = BorderAlignFunction.apply - - -class BorderAlign(nn.Module): - r"""Border align pooling layer. - - Applies border_align over the input feature based on predicted bboxes. - The details were described in the paper - `BorderDet: Border Feature for Dense Object Detection - `_. - - For each border line (e.g. top, left, bottom or right) of each box, - border_align does the following: - 1. uniformly samples `pool_size`+1 positions on this line, involving \ - the start and end points. - 2. the corresponding features on these points are computed by \ - bilinear interpolation. - 3. max pooling over all the `pool_size`+1 positions are used for \ - computing pooled feature. - - Args: - pool_size (int): number of positions sampled over the boxes' borders - (e.g. top, bottom, left, right). - - """ - - def __init__(self, pool_size): - super(BorderAlign, self).__init__() - self.pool_size = pool_size - - def forward(self, input, boxes): - """ - Args: - input: Features with shape [N,4C,H,W]. Channels ranged in [0,C), - [C,2C), [2C,3C), [3C,4C) represent the top, left, bottom, - right features respectively. - boxes: Boxes with shape [N,H*W,4]. Coordinate format (x1,y1,x2,y2). - - Returns: - Tensor: Pooled features with shape [N,C,H*W,4]. The order is - (top,left,bottom,right) for the last dimension. - """ - return border_align(input, boxes, self.pool_size) - - def __repr__(self): - s = self.__class__.__name__ - s += f'(pool_size={self.pool_size})' - return s diff --git a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmseg/models/losses/__init__.py b/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmseg/models/losses/__init__.py deleted file mode 100644 index beca72045694273d63465bac2f27dbc6672271db..0000000000000000000000000000000000000000 --- a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmseg/models/losses/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -from .accuracy import Accuracy, accuracy -from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, - cross_entropy, mask_cross_entropy) -from .dice_loss import DiceLoss -from .lovasz_loss import LovaszLoss -from .utils import reduce_loss, weight_reduce_loss, weighted_loss - -__all__ = [ - 'accuracy', 'Accuracy', 'cross_entropy', 'binary_cross_entropy', - 'mask_cross_entropy', 'CrossEntropyLoss', 'reduce_loss', - 'weight_reduce_loss', 'weighted_loss', 'LovaszLoss', 'DiceLoss' -] diff --git a/spaces/terfces0erbo/CollegeProjectV2/Bhaag Milkha Bhaag Movie With English Subtitles !!BETTER!! Download Torrent.md b/spaces/terfces0erbo/CollegeProjectV2/Bhaag Milkha Bhaag Movie With English Subtitles !!BETTER!! Download Torrent.md deleted file mode 100644 index 1669eefb1f96614bd797f227a3edbd1fee02cbca..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Bhaag Milkha Bhaag Movie With English Subtitles !!BETTER!! Download Torrent.md +++ /dev/null @@ -1,23 +0,0 @@ -
    -``` -

    How to Watch Bhaag Milkha Bhaag Movie with English Subtitles Online

    -

    Bhaag Milkha Bhaag is a 2013 Indian biographical sports drama film based on the life of Milkha Singh, a former Indian track and field sprinter who was the first Indian to win an individual athletics gold medal at the Commonwealth Games. The film stars Farhan Akhtar as Milkha Singh and Sonam Kapoor as his love interest. The film was directed by Rakeysh Omprakash Mehra and produced by Viacom 18 Motion Pictures and Rakeysh Omprakash Mehra Pictures.

    -

    If you are looking for a way to watch Bhaag Milkha Bhaag movie with English subtitles online, you might be tempted to download a torrent file from an illegal website. However, this is not only risky for your device and personal data, but also unethical and illegal. Downloading pirated content is a violation of the Indian Copyright Act of 1957 and can result in fines or imprisonment.

    -

    Bhaag Milkha Bhaag Movie With English Subtitles Download Torrent


    Download ✫✫✫ https://bytlly.com/2uGkbE



    -

    The good news is that there are legal and safe ways to watch Bhaag Milkha Bhaag movie with English subtitles online. Here are some of them:

    -
      -
    • Netflix: Netflix is a popular streaming service that offers a wide range of movies and shows from different genres and languages. You can watch Bhaag Milkha Bhaag movie with English subtitles on Netflix if you have a subscription. You can also download the movie for offline viewing on your device.
    • -
    • Amazon Prime Video: Amazon Prime Video is another streaming service that offers a variety of content, including movies, shows, originals, and live sports. You can watch Bhaag Milkha Bhaag movie with English subtitles on Amazon Prime Video if you have a Prime membership. You can also download the movie for offline viewing on your device.
    • -
    • YouTube: YouTube is a free video-sharing platform that allows users to upload, watch, and share videos. You can watch Bhaag Milkha Bhaag movie with English subtitles on YouTube if you rent or buy the movie from the official channel of Viacom 18 Motion Pictures. You can also download the movie for offline viewing on your device.
    • -
    -

    These are some of the legal and safe ways to watch Bhaag Milkha Bhaag movie with English subtitles online. We hope you enjoy watching this inspiring and entertaining film.

    -``` - -``` -

    Bhaag Milkha Bhaag movie is not only a biopic of a legendary athlete, but also a tribute to the spirit of India. The film showcases the historical and cultural events that shaped Milkha Singh's life and career, such as the Partition of India, the Indo-Pak wars, and the Asian Games. The film also explores the personal and emotional aspects of Milkha Singh's journey, such as his childhood trauma, his family bonds, his romance, and his rivalry with Abdul Khaliq, a Pakistani sprinter.

    -

    The film received critical acclaim and commercial success upon its release. It won several awards and nominations, including two National Film Awards, five Filmfare Awards, and ten Screen Awards. It was also India's official entry for the Best Foreign Language Film category at the 86th Academy Awards, but it did not make the final shortlist. The film was praised for its direction, screenplay, cinematography, music, editing, and performances. Farhan Akhtar's portrayal of Milkha Singh was especially lauded for its authenticity and dedication.

    -

    Bhaag Milkha Bhaag movie is a must-watch for anyone who loves sports, history, or cinema. It is a film that inspires and entertains with its powerful story and stunning visuals. It is a film that celebrates the life and legacy of Milkha Singh, who is also known as "The Flying Sikh".

    -

    -```

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/terfces0erbo/CollegeProjectV2/Bhrigusamhitainmarathipdf.md b/spaces/terfces0erbo/CollegeProjectV2/Bhrigusamhitainmarathipdf.md deleted file mode 100644 index db65cb16449ae3f05636f89cc8ff0f67d797ad4e..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Bhrigusamhitainmarathipdf.md +++ /dev/null @@ -1,6 +0,0 @@ -

    bhrigusamhitainmarathipdf


    Download File ---> https://bytlly.com/2uGjOR



    - -More Status Video : Karan Preeta Naznina Song Status Video Free Download Bhrigusamhitainmarathipdf >>> DOWNLOAD Read / Download Bhrigu Sanhi ... 1fdad05405
    -
    -
    -

    diff --git a/spaces/terfces0erbo/CollegeProjectV2/Download Mastercam X9 Full Crack Software.md b/spaces/terfces0erbo/CollegeProjectV2/Download Mastercam X9 Full Crack Software.md deleted file mode 100644 index 503178f633882e44d4889827e6715858ce4a04f5..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Download Mastercam X9 Full Crack Software.md +++ /dev/null @@ -1,6 +0,0 @@ -

    download mastercam x9 full crack software


    DOWNLOAD ✪✪✪ https://bytlly.com/2uGkAh



    -
    -January 19, 2022 — Mastercam x9 Crack is the oldest CAD design software in development . It was developed by the CAD company in 1983 in many industries, including automotive, aerospace, instrumentation, etc., as well as in schools. It comes with a large . NET Compact Framework which makes it easy to use with modern browsers. It also allows you to use external applications such as AutoCAD, SolidWorks, etc. without any modifications. Once you have purchased a license, you can create 3D models in it and then send them to any other CAD software for processing. In the past, Mastercam x9 and its versions had some performance and debugging issues. 8a78ff9644
    -
    -
    -

    diff --git a/spaces/thejagstudio/procom/flipkart/views.py b/spaces/thejagstudio/procom/flipkart/views.py deleted file mode 100644 index 2cd2feb9535b20bc509c8af4f9c743a536bac426..0000000000000000000000000000000000000000 --- a/spaces/thejagstudio/procom/flipkart/views.py +++ /dev/null @@ -1,227 +0,0 @@ -from django.shortcuts import render -from rest_framework.response import Response -from rest_framework.decorators import api_view -import http.client -import json -import requests -from bs4 import BeautifulSoup -# Create your views here. - - -def sessionIdGenrator(): - conn = http.client.HTTPSConnection("www.amazon.in") - payload = '' - headers = {} - conn.request("GET", "/", payload, headers) - res = conn.getresponse() - data = res.read() - response = data.decode("utf-8") - ue_sid = response.split("ue_sid =")[1].split(',')[0].split("'")[1] - ue_mid = response.split("ue_mid =")[1].split(',')[0].split("'")[1] - return ue_sid, ue_mid - - -def searchAPI(query): - conn = http.client.HTTPSConnection("2.rome.api.flipkart.com") - payload = json.dumps({ - "query": query, - "marketPlaceId": "FLIPKART", - "types": [ - "QUERY", - "QUERY_STORE", - "PRODUCT", - "RICH", - "PARTITION" - ], - "rows": 10 - }) - headers = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36', - 'X-User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 FKUA/website/42/website/Desktop', - 'Content-Type': 'application/json' - } - conn.request("POST", "/api/4/discover/autosuggest", payload, headers) - res = conn.getresponse() - data = res.read() - response = data.decode("utf-8") - return json.loads(response) - - -def getAllProduct(query, page): - - url = "https://2.rome.api.flipkart.com/api/4/page/fetch" - - payload = json.dumps({"pageUri":"/search?q="+query+"&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off","pageContext":{"fetchSeoData":True,"paginatedFetch":False,"pageNumber":page},"requestContext":{"type":"BROWSE_PAGE"}}) - headers = { - 'Accept': '*/*', - 'Accept-Language': 'en-US,en;q=0.9,gu;q=0.8', - 'Connection': 'keep-alive', - 'Content-Type': 'application/json', - 'Origin': 'https://www.flipkart.com', - 'X-User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 FKUA/website/42/website/Desktop' - } - - data=[] - response = requests.request("POST", url, headers=headers, data=payload) - slots = response.json()["RESPONSE"]["slots"] - for slot in slots: - if slot["slotType"] == "WIDGET": - if slot["widget"]["type"] == "PRODUCT_SUMMARY": - temp = {} - try: - title = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["titles"]["title"] - temp["title"] = title - except: - pass - try: - link = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["smartUrl"] - temp["link"] = link - except: - pass - try: - keySpecs = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["keySpecs"] - temp["keySpecs"] = keySpecs - except: - pass - try: - minKeySpecs= slot["widget"]["data"]["products"][0]["productInfo"]["value"]["minKeySpecs"] - temp["minKeySpecs"] = minKeySpecs - except: - pass - media = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["media"]["images"] - images = [] - for i in media: - images.append(i["url"].replace("{@width}", "1000").replace("{@height}", "1000").replace("{@quality}", "100")) - try: - temp["imgs"] = images - except: - pass - try: - price = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["pricing"]["finalPrice"]["value"] - temp["price"] = price - except: - pass - try: - fullPrice = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["pricing"]["mrp"]["value"] - temp["fullPrice"] = fullPrice - except: - pass - try: - symbol = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["pricing"]["mrp"]["currency"] - if symbol == "INR": - symbol = "₹" - if symbol == "USD": - symbol = "$" - if symbol == "EUR": - symbol = "€" - if symbol == "GBP": - symbol = "£" - if symbol == "AUD": - symbol = "A$" - temp["symbol"] = symbol - except: - pass - try: - stars = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["rating"]["average"] - temp["stars"] = str(stars)+ " out of 5 stars" - except: - pass - try: - starCount = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["rating"]["roundOffCount"] - temp["starCount"] = starCount - except: - pass - try: - reviews = slot["widget"]["data"]["products"][0]["productInfo"]["value"]["rating"]["reviewCount"] - temp["reviews"] = reviews - except: - pass - try: - offer = "" - for i in slot["widget"]["data"]["products"][0]["snippets"]: - for j in i["data"]: - offer = offer + j["value"]["text"] - offer = offer + ", " - offer = offer[:-2] - temp["offer"] = offer - except: - pass - data.append(temp) - return data - - -@api_view(['GET']) -def getProductsList(request): - query = (request.GET.get('query')).replace(" ", "+") - try: - page = (request.GET.get('page')) - except: - page = 1 - if page == None: - page = 1 - data = getAllProduct(query, page) - return Response({"data": data}) - - -@api_view(['GET']) -def getProductDetail(request): - productId = request.GET.get('id') - conn = http.client.HTTPSConnection("www.amazon.in") - payload = '' - headers = {} - conn.request("GET", "/dp/"+productId+"/", payload, headers) - res = conn.getresponse() - data = res.read() - response = data.decode("utf-8") - data = {} - soup = BeautifulSoup(response, features="html5lib") - #title = response.split('id="productTitle"')[1].split(">")[1].split("")[1].split(" List[str]: - if self.pdf: - text = re.sub(r"\n{3,}", "\n", text) - text = re.sub('\s', ' ', text) - text = text.replace("\n\n", "") - sent_sep_pattern = re.compile('([﹒﹔﹖﹗.。!?]["’”」』]{0,2}|(?=["‘“「『]{1,2}|$))') # del :; - sent_list = [] - for ele in sent_sep_pattern.split(text): - if sent_sep_pattern.match(ele) and sent_list: - sent_list[-1] += ele - elif ele: - sent_list.append(ele) - return sent_list diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Chill Bump - Ego Trip (2014).rar [HOT].md b/spaces/tialenAdioni/chat-gpt-api/logs/Chill Bump - Ego Trip (2014).rar [HOT].md deleted file mode 100644 index 8e33fc9e3af154f17262bed8144a780910881c18..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Chill Bump - Ego Trip (2014).rar [HOT].md +++ /dev/null @@ -1,17 +0,0 @@ - -

    Chill Bump - Ego Trip (2014): A Hip Hop Masterpiece

    -

    If you are looking for a hip hop album that will blow your mind with its originality, creativity and skill, look no further than Chill Bump - Ego Trip (2014). This album is the debut full-length release by the French duo Chill Bump, composed of rapper Miscellaneous and producer Bankal. It features 11 tracks of pure fire, blending rap, electro, jazz and rock influences.

    -

    Chill Bump - Ego Trip (2014).rar


    Download File === https://urlcod.com/2uK88Y



    -

    In this article, we will review the album and tell you why you should download it right now. We will also provide you with a link to download the album in .rar format, so you can enjoy it on any device.

    -

    What is Chill Bump - Ego Trip (2014) about?

    -

    The album title Ego Trip refers to the journey of self-discovery and self-expression that Chill Bump undertakes through their music. The album explores various themes such as identity, ambition, success, failure, love, hate, society and politics. The lyrics are witty, clever and sometimes sarcastic, but always honest and authentic. The album also showcases Chill Bump's versatility and diversity, as they switch from fast-paced bangers to smooth grooves, from English to French, from serious topics to humorous ones.

    -

    The album opens with Alpha, a short intro that sets the tone for the rest of the album. It features a sample of a speech by Malcolm X, followed by a powerful verse by Miscellaneous that introduces himself and his partner Bankal. The track ends with a catchy chorus that repeats the phrase "We are Chill Bump".

    -

    The next track is The Memo, one of the most popular songs on the album. It is a hard-hitting anthem that showcases Chill Bump's confidence and skills. The beat is energetic and infectious, with a heavy bass and a horn section. The lyrics are full of punchlines and metaphors that display Chill Bump's rap prowess. The chorus is catchy and memorable, with Miscellaneous declaring "We don't need no memo to know we're dope".

    -

    -

    The third track is I Get the Job Done, a smooth and funky tune that pays homage to the classic hip hop song by Big Daddy Kane. The beat is groovy and jazzy, with a guitar riff and a saxophone solo. The lyrics are humorous and playful, as Chill Bump brag about their abilities in various fields, from music to sports to sex. The chorus is catchy and fun, with Miscellaneous repeating "I get the job done" in different languages.

    -

    The fourth track is Not Today, a dark and gritty song that deals with the struggles of life and the challenges of pursuing one's dreams. The beat is ominous and heavy, with a distorted guitar and a piano melody. The lyrics are introspective and realistic, as Chill Bump reflect on their failures, doubts and fears. The chorus is simple but effective, with Miscellaneous saying "Not today" to all the obstacles that stand in his way.

    -

    The fifth track is One Way Ticket, a soulful and melancholic song that expresses Chill Bump's desire to escape from their problems and travel around the world. The beat is mellow and atmospheric, with a guitar loop and a vocal sample. The lyrics are poetic and emotional, as Chill Bump describe their fantasies of visiting different places and meeting different people. The chorus is catchy and sad, with Miscellaneous singing "I need a one way ticket out of here".

    -

    The sixth track is Beat Goes On, a upbeat and optimistic song that celebrates life and music. The beat is lively and cheerful, with a piano chord progression and a trumpet solo. The lyrics are positive and inspirational, as Chill Bump encourage themselves and their listeners to keep going despite the hardships. The chorus is catchy and uplifting, with Miscellaneous chanting "The beat goes on" in different languages.

    -

    The seventh track is 01.01, a short interlude that marks the transition from the first half of the album to the second half. It features a sample of a countdown followed by fireworks, symbolizing the start

    e93f5a0c3f
    -
    -
    \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Free PDF of Operation Research Book By Pk Gupta A Review of OR Models and Algorithms.md b/spaces/tialenAdioni/chat-gpt-api/logs/Free PDF of Operation Research Book By Pk Gupta A Review of OR Models and Algorithms.md deleted file mode 100644 index 03cacf8243543cf0774d01d5084a7192682eed68..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Free PDF of Operation Research Book By Pk Gupta A Review of OR Models and Algorithms.md +++ /dev/null @@ -1,154 +0,0 @@ - -

    Operation Research Book By Pk Gupta Free Download

    -

    Operation research is a branch of mathematics that deals with the analysis and optimization of complex systems and processes. It is widely used in engineering, management, economics, statistics, and other fields to solve problems involving decision making, resource allocation, scheduling, planning, and control.

    -

    If you are looking for a comprehensive and easy-to-understand textbook on operation research, you may want to check out the book by P. K. Gupta and D. S. Hira. This book covers all the essential topics of operation research, such as linear programming, transportation and assignment problems, network analysis, game theory, inventory models, queuing theory, simulation, dynamic programming, and more.

    -

    Operation Research Book By Pk Gupta Free Download


    DOWNLOAD –––––>>> https://urlcod.com/2uK6vG



    -

    The book also provides numerous examples, exercises, and case studies to illustrate the applications of operation research in various domains. It is suitable for students of mathematics, statistics, commerce, engineering, and management of all Indian universities. It is also useful for IAS and other competitive examinations.

    -

    How to Download Operation Research Book By Pk Gupta Free

    -

    If you want to download the operation research book by P. K. Gupta and D. S. Hira for free, you have a few options. One of them is to visit the Internet Archive website, where you can find a scanned copy of the book in PDF format. You can either read it online or download it to your device.

    -

    Another option is to visit the PDF Room website, where you can find a digital version of the book in PDF format. You can also convert it to other formats, such as EPUB or MOBI. You can preview the book before downloading it or view it on Amazon.

    -

    A third option is to use a search engine like Google or Bing to find other websites that offer the book for free download. However, you should be careful about the quality and legality of these sources. Some of them may contain viruses or malware that can harm your device or compromise your privacy.

    -

    Benefits of Reading Operation Research Book By Pk Gupta

    -

    Reading the operation research book by P. K. Gupta and D. S. Hira can provide you with many benefits. Some of them are:

    -
      -
    • You will learn the fundamental concepts and techniques of operation research and how to apply them to real-world problems.
    • -
    • You will improve your analytical and problem-solving skills and enhance your logical thinking and creativity.
    • -
    • You will gain a deeper understanding of various fields and disciplines that use operation research methods and models.
    • -
    • You will prepare yourself for higher studies or professional careers in operation research or related areas.
    • -
    • You will enjoy reading a well-written and engaging book that explains complex topics in a simple and clear manner.
    • -
    -

    Therefore, if you are interested in learning more about operation research or improving your skills in this field, you should definitely download the operation research book by P. K. Gupta and D. S. Hira for free today.

    -

    Reviews of Operation Research Book By Pk Gupta

    -

    Many readers have praised the operation research book by P. K. Gupta and D. S. Hira for its clarity, comprehensiveness, and practicality. Here are some of the reviews from the Internet Archive website:

    -

    How to download Operation Research Book By Pk Gupta for free
    -Operation Research Book By Pk Gupta PDF download link
    -Best sites to download Operation Research Book By Pk Gupta
    -Operation Research Book By Pk Gupta solutions manual free download
    -Operation Research Book By Pk Gupta ebook download
    -Operation Research Book By Pk Gupta free online reading
    -Operation Research Book By Pk Gupta review and summary
    -Operation Research Book By Pk Gupta chapter-wise notes
    -Operation Research Book By Pk Gupta MCQs and exercises
    -Operation Research Book By Pk Gupta latest edition free download
    -Operation Research Book By Pk Gupta epub and mobi format
    -Operation Research Book By Pk Gupta torrent download
    -Operation Research Book By Pk Gupta Google Drive download
    -Operation Research Book By Pk Gupta Flipkart and Amazon price
    -Operation Research Book By Pk Gupta hard copy free delivery
    -Operation Research Book By Pk Gupta author biography and contact
    -Operation Research Book By Pk Gupta lecture slides and videos
    -Operation Research Book By Pk Gupta reference books and citations
    -Operation Research Book By Pk Gupta syllabus and curriculum
    -Operation Research Book By Pk Gupta previous year question papers
    -Operation Research Book By Pk Gupta case studies and examples
    -Operation Research Book By Pk Gupta applications and scope
    -Operation Research Book By Pk Gupta projects and assignments
    -Operation Research Book By Pk Gupta quizzes and tests
    -Operation Research Book By Pk Gupta online courses and tutorials
    -Operation Research Book By Pk Gupta interview questions and answers
    -Operation Research Book By Pk Gupta research papers and publications
    -Operation Research Book By Pk Gupta blogs and forums
    -Operation Research Book By Pk Gupta podcasts and webinars
    -Operation Research Book By Pk Gupta scholarships and grants
    -Operation Research Book By Pk Gupta competitions and events
    -Operation Research Book By Pk Gupta software and tools
    -Operation Research Book By Pk Gupta career opportunities and salary
    -Operation Research Book By Pk Gupta certification and accreditation
    -Operation Research Book By Pk Gupta feedback and ratings
    -Operation Research Book By Pk Gupta FAQs and tips
    -Operation Research Book By Pk Gupta comparison and analysis
    -Operation Research Book By Pk Gupta pros and cons
    -Operation Research Book By Pk Gupta advantages and disadvantages
    -Operation Research Book By Pk Gupta benefits and drawbacks
    -Operation Research Book By Pk Gupta features and highlights
    -Operation Research Book By Pk Gupta updates and news
    -Operation Research Book By Pk Gupta alternatives and substitutes
    -Operation Research Book By Pk Gupta recommendations and suggestions
    -Operation Research Book By Pk Gupta testimonials and reviews
    -Operation Research Book By Pk Gupta discounts and offers
    -Operation Research Book By Pk Gupta coupons and codes
    -Operation Research Book By Pk Gupta free trial and sample chapters
    -Operation Research Book By Pk Gupta plagiarism check and quality assurance
    -Operation Research Book By Pk Gupta ISBN and edition details

    -
    -

    "This book is very good for beginners as well as for advanced learners. It covers all the topics of operation research in a systematic and lucid manner. The examples and exercises are very helpful to understand the concepts and applications."

    -

    "This is one of the best books on operation research I have ever read. It is very well written and organized. It explains the theory and methods of operation research with simple language and illustrations. It also provides real-life case studies to show the relevance and usefulness of operation research."

    -

    "I highly recommend this book to anyone who wants to learn operation research or improve their skills in this field. It is a complete and comprehensive guide that covers all the aspects of operation research. It is also very easy to follow and understand."

    -
    -
    Conclusion
    -

    Operation research is a fascinating and useful subject that can help you solve complex problems and optimize systems and processes. If you want to learn more about this subject or enhance your knowledge and skills, you should download the operation research book by P. K. Gupta and D. S. Hira for free today.

    -

    This book is a masterpiece that covers all the essential topics of operation research in a simple and clear way. It also provides numerous examples, exercises, and case studies to help you apply operation research to various domains. It is suitable for students, teachers, researchers, and professionals of all Indian universities.

    -

    So, what are you waiting for? Download the operation research book by Pk Gupta free today and start learning this amazing subject.

    -
    FAQs About Operation Research Book By Pk Gupta
    -

    You may have some questions about the operation research book by P. K. Gupta and D. S. Hira. Here are some of the frequently asked questions and their answers:

    -
      -
    1. What is the edition and year of publication of the book?
      -The book is the ninth edition and was published in 2014 by S. Chand & Company Pvt. Ltd.
    2. -
    3. What are the contents of the book?
      -The book has 36 chapters divided into six parts: Part I - Introduction, Part II - Linear Programming, Part III - Transportation and Assignment Problems, Part IV - Network Analysis, Part V - Advanced Topics in Operation Research, and Part VI - Appendices.
    4. -
    5. How can I access the solutions of the exercises in the book?
      -The book provides answers to selected exercises at the end of each chapter. You can also find the complete solutions manual online on various websites.
    6. -
    7. Is the book suitable for self-study?
      -Yes, the book is suitable for self-study as it explains the concepts and methods of operation research in a simple and clear way. It also provides numerous examples, exercises, and case studies to help you practice and apply operation research to various domains.
    8. -
    9. Where can I buy the book?
      -You can buy the book online or offline from various sources, such as Amazon, Flipkart, Snapdeal, etc. You can also download the book for free from the Internet Archive or PDF Room websites.
    10. -
    -

    If you have any other questions about the operation research book by Pk Gupta free download, feel free to ask me in the comments section below.

    -Comparison of Operation Research Book By Pk Gupta with Other Books -

    There are many other books on operation research available in the market. How does the operation research book by P. K. Gupta and D. S. Hira compare with them? Here are some of the points of comparison:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    BookAuthor(s)ProsCons
    Operations Research: An IntroductionH.A. Taha- Covers a wide range of topics in operation research
    - Provides clear explanations and examples
    - Includes software applications and online resources
    - May be too advanced for some readers
    - May not cover some topics in depth
    - May have some errors or typos
    Introduction to Operations ResearchF.S. Hillier and G.J. Lieberman- Provides a comprehensive and rigorous treatment of operation research
    - Emphasizes modeling and algorithmic approaches
    - Includes case studies and real-world applications
    - May be too mathematical for some readers
    - May not include some recent developments or techniques
    - May be too expensive for some readers
    Operations Research: Principles and PracticeR. Ravindran, D.T. Phillips, and J.J. Solberg- Focuses on the principles and practice of operation research
    - Balances theory and applications
    - Incorporates spreadsheet modeling and optimization tools
    - May not cover some topics comprehensively
    - May have some outdated or irrelevant examples
    - May have some errors or inconsistencies
    Operations Research: A Textbook for Students of Mathematics, Statistics Commerce, Engineering and Management of All Indian UniversitiesP.K. Gupta and D.S. Hira- Covers all the essential topics of operation research in a simple and clear way
    - Provides numerous examples, exercises, and case studies
    - Suitable for students, teachers, researchers, and professionals of all Indian universities
    - May not include some advanced or specialized topics
    - May not follow some standard notations or conventions
    - May have some errors or omissions
    - -

    As you can see, each book has its own strengths and weaknesses. You can choose the book that best suits your needs and preferences. However, if you are looking for a book that is comprehensive, easy-to-understand, practical, and relevant to the Indian context, you should download the operation research book by Pk Gupta free today.

    -Challenges and Opportunities of Operation Research -

    Operation research is a dynamic and evolving field that faces many challenges and opportunities in the modern world. Some of the challenges and opportunities are:

    -
      -
    • Challenge: Dealing with uncertainty and risk in complex and dynamic environments
      -Opportunity: Developing robust and flexible models and methods that can handle uncertainty and risk effectively and efficiently
    • -
    • Challenge: Integrating multiple criteria and stakeholders in decision making
      -Opportunity: Developing multicriteria and multiobjective optimization techniques that can balance conflicting goals and preferences of different stakeholders
    • -
    • Challenge: Incorporating human factors and behavioral aspects in operation research
      -Opportunity: Developing behavioral operation research approaches that can account for human judgment, emotions, biases, and motivations in operation research
    • -
    • Challenge: Addressing ethical, social, and environmental issues in operation research
      -Opportunity: Developing ethical operation research frameworks that can consider the impacts and implications of operation research on society and nature
    • -
    • Challenge: Leveraging big data and artificial intelligence in operation research
      -Opportunity: Developing data-driven and intelligent operation research methods that can exploit the potential of big data and artificial intelligence for operation research
    • -
    -

    These are some of the challenges and opportunities of operation research that require further research and innovation. By overcoming these challenges and seizing these opportunities, operation research can contribute to the advancement of science, technology, management, and society.

    -Conclusion -

    Operation research is a fascinating and useful subject that can help you solve complex problems and optimize systems and processes. It is widely used in various fields and disciplines to improve decision making, resource allocation, scheduling, planning, and control.

    -

    If you want to learn more about operation research or enhance your knowledge and skills in this field, you should download the operation research book by P. K. Gupta and D. S. Hira for free today. This book is a comprehensive and easy-to-understand textbook that covers all the essential topics of operation research in a simple and clear way. It also provides numerous examples, exercises, and case studies to help you apply operation research to various domains. It is suitable for students, teachers, researchers, and professionals of all Indian universities.

    -

    In this article, we have discussed the features, benefits, reviews, FAQs, comparison, challenges, and opportunities of the operation research book by Pk Gupta free download. We hope that this article has helped you understand the value and importance of this book and motivated you to download it today.

    -

    So, what are you waiting for? Download the operation research book by Pk Gupta free today and start learning this amazing subject.

    679dcb208e
    -
    -
    \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/How to Troubleshoot and Update Items PC TV Expert Driver for Your TV Capture Card.md b/spaces/tialenAdioni/chat-gpt-api/logs/How to Troubleshoot and Update Items PC TV Expert Driver for Your TV Capture Card.md deleted file mode 100644 index 4b1e79003ea4de48b7f5f91ebb0d871a1982b07e..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/How to Troubleshoot and Update Items PC TV Expert Driver for Your TV Capture Card.md +++ /dev/null @@ -1,21 +0,0 @@ - -

    Items PC TV Expert Driver: How to Install and Use a TV Capture Card

    - Do you want to watch and record your favorite TV shows on your computer? Do you want to edit and convert your videos into different formats? Do you want to stream and share your videos with your friends and family? If you answered yes to any of these questions, then you might be interested in getting a TV capture card for your PC. A TV capture card is a device that allows you to connect your TV signal source (such as cable, antenna, or satellite) to your computer and capture the video and audio signals. With a TV capture card, you can turn your PC into a personal video recorder (PVR) and enjoy various features that enhance your viewing experience. In this article, we will explain what a TV capture card is, how to choose one, how to install it, and how to use it. We will also introduce you to one of the popular TV capture cards on the market: the Items PC TV Expert Driver.

    What is a TV Capture Card?

    - A TV capture card is also known as a TV tuner card or a video capture card. It is a type of expansion card that plugs into a PCI or PCIe slot on your motherboard. It has one or more inputs for connecting your TV signal source, such as coaxial cable, composite video, S-video, or HDMI. It also has one or more outputs for connecting your monitor, speakers, or headphones. A TV capture card works by converting the analog or digital TV signals into data that can be stored on your hard drive or displayed on your screen. Depending on the model and software, you can also use a TV capture card to: - Watch live TV on your PC - Record TV shows and movies for later viewing - Pause, rewind, and fast-forward live TV - Schedule recordings and reminders - Edit and convert videos into different formats - Stream videos to other devices or online platforms - Share videos with others via email or social media

    Benefits of Using a TV Capture Card

    - There are many benefits of using a TV capture card for your PC. Some of them are: - You can save money by cutting the cord and using free over-the-air (OTA) channels or online streaming services instead of paying for cable or satellite subscriptions. - You can save space by eliminating the need for a separate set-top box or DVR device. - You can customize your viewing experience by choosing the software and features that suit your needs and preferences. - You can enhance your video quality by adjusting the resolution, frame rate, bitrate, and other settings. - You can improve your audio quality by using surround sound or noise reduction features. - You can access more content by using multiple tuners or sources, such as OTA channels, cable channels, satellite channels, online streaming services, DVDs, Blu-rays, camcorders, game consoles, etc.

    Types of TV Capture Cards

    - There are different types of TV capture cards available on the market. Some of the common ones are: - Analog TV capture cards: These are the oldest and cheapest type of TV capture cards. They can only receive analog signals from sources such as VCRs, camcorders, or older TVs. They have low resolution and quality compared to digital signals. They are also prone to interference and noise. However, they are still useful for capturing old videos or converting them into digital formats. - Digital TV capture cards: These are the most common type of TV capture cards today. They can receive digital signals from sources such as OTA channels, cable channels, satellite channels, DVDs, Blu-rays, etc. They have high resolution and quality compared to analog signals. They are also more stable and secure than analog signals. However, they may require additional hardware or software to decrypt encrypted channels or formats. - Hybrid TV capture cards: These are a combination of analog and digital TV capture cards. They can receive both analog and digital signals from various sources. They offer more versatility and compatibility than single-type cards. However, they may also have higher cost and complexity than single-type cards.

    How to Choose a TV Capture Card

    - Before you buy a TV capture card for your PC, you should consider some factors that may affect your choice. Some of them are:

    Compatibility

    - You should check if the TV capture card is compatible with your PC hardware and software. For example: - You should check if the TV capture card fits into an available PCI or PCIe slot on your motherboard. - You should check if the TV capture card supports your operating system (such as Windows XP SP2, Windows Vista, Windows 7, Windows 10, etc.) - You should check if the TV capture card supports your video format (such as NTSC, PAL, SECAM, ATSC, DVB-T, DVB-S, DVB-C, etc.) - You should check if the TV capture card supports your audio format (such as stereo, Dolby Digital, DTS, etc.) - You should check if the TV capture card supports your input source (such as coaxial cable , composite video , S-video , HDMI, etc.) - You should check if the TV capture card supports your output device (such as monitor , speakers , headphones , etc.)

    Features

    - You should check what features the TV capture card offers and if they meet your needs and preferences. For example: - You should check how many tuners the TV capture card has and if they allow you to watch or record multiple channels at once. - You should check what software the TV capture card comes with and if it provides functions such as watching live TV , recording shows , pausing live TV , scheduling recordings , editing videos , converting videos , streaming videos, sharing videos, etc. - You should check what additional features the TV capture card has and if they enhance your viewing experience such as remote control , electronic program guide (EPG)[^1 ^][ ^4 ^ ], closed captioning[ ^ 1 ^ ][ ^ 4 ^ ], parental control[ ^ 1 ^ ][ ^ 4 ^ ], picture-in-picture (PIP)[ ^ 4 ^ ], time-shifting[ ^ 4 ^ ], etc.

    Price

    - You should compare the prices of different models and brands of TV capture cards and see which one offers the best value for money. You should also consider other costs such as installation fees[ ^ 2 ^ ], subscription fees[ ^ 2 ^ ], maintenance fees[ ^ 2 ^ ], etc.

    How to Install a TV Capture Card

    - Once you have chosen a suitable TV capture card for your PC, you need to install it properly. The installation process may vary depending on the model and brand of the card, but generally it involves two steps: hardware installation and software installation.

    Hardware Installation

    - To install the hardware part of the TV capture card, you need to follow these steps: - Turn off your PC and unplug it from the power source. - Open the case of your PC and locate an available PCI or PCIe slot on your motherboard. - Remove any screws or brackets that secure the slot cover. - Align the edge connector of the TV capture card with the slot and gently push it in until it snaps into place. - Secure the card with screws or brackets if needed. - Connect the input source (such as cable, antenna, or satellite) to the input port on the card using an appropriate cable (such as coaxial cable[ ^ 2 ^ ], composite video cable[ ^ 2 ^ ], S-video cable[ ^ 2 ^ ], HDMI cable[ ^ 2 ^ ], etc.) - Connect the output device (such as monitor , speakers , headphones , etc.) to the output port on the card using an appropriate cable (such as VGA cable, DVI cable, HDMI cable , audio cable , etc.)

    Software Installation

    - To install the software part of the TV capture card, you need to follow these steps: - Insert the installation disc that came with the TV capture card into the CD or DVD-ROM drive of your PC. - Run the setup program and follow the instructions on the screen to install the drivers and software for the TV capture card. - If prompted, restart your PC to complete the installation. - Launch the TV capture software that came with the TV capture card or use another compatible software of your choice. - Configure the settings of the TV capture software according to your preferences, such as video source, channel scan, recording format, video quality, audio quality, etc.

    Troubleshooting Tips

    - If you encounter any problems while installing or using the TV capture card, you can try some of these tips: - Make sure the TV capture card is properly inserted into the PCI or PCIe slot and secured with screws or brackets. - Make sure the input and output cables are firmly connected to the TV capture card and the source and device. - Make sure you have installed the latest drivers and software for the TV capture card from the manufacturer's website or disc. - Make sure you have selected the correct input source and output device in the TV capture software settings. - Make sure you have adjusted the volume and mute settings on your PC and external audio system. - Check for any interference or noise from other devices or cables near the TV capture card or source. - Check for any updates or patches for your operating system or TV capture software.

    How to Use a TV Capture Card

    - After you have installed and configured the TV capture card, you can start using it to watch and record TV shows on your PC. Here are some of the basic functions you can perform with a TV capture card:

    Watching and Recording TV Shows

    - To watch and record TV shows on your PC using a TV capture card, you need to follow these steps: - Launch the TV capture software that came with the TV capture card or use another compatible software of your choice. - Select the input source that corresponds to your TV signal source (such as OTA channels, cable channels, satellite channels, etc.) - Scan for available channels and save them in a channel list. - Use the remote control or mouse to navigate through the channel list and select a channel to watch. - Use the playback controls to pause, rewind, fast-forward, or skip live TV. - Use the recording controls to start, stop, or schedule a recording of a TV show or movie. - Use the file manager to access, play, delete, or rename your recorded files.

    Editing and Converting Videos

    - To edit and convert videos on your PC using a TV capture card, you need to follow these steps: - Launch the video editing software that came with the TV capture card or use another compatible software of your choice. - Import your recorded files or other video files from your hard drive or external storage device into the video editing software. - Use the editing tools to trim, crop, rotate, split, merge, add effects, transitions, titles, subtitles, etc. to your videos. - Use the conversion tools to change the format, resolution, frame rate, bitrate, codec, etc. of your videos according to your needs and preferences. - Export your edited and converted videos to your hard drive or external storage device.

    Streaming and Sharing Videos

    - To stream and share videos on your PC using a TV capture card, you need to follow these steps: - Launch try downloading the latest drivers and software from the manufacturer's website or disc.

    -

    items pc tv expert driver


    Download Filehttps://urlcod.com/2uK9n1



    0a6ba089eb
    -
    -
    \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Bubble APK and Join Millions of Players in the Bubble Shooter Craze.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Bubble APK and Join Millions of Players in the Bubble Shooter Craze.md deleted file mode 100644 index dd55288e994c11b4760d847073290768d5b90742..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Bubble APK and Join Millions of Players in the Bubble Shooter Craze.md +++ /dev/null @@ -1,116 +0,0 @@ - -

    Bubble APK Download: How to Play and Enjoy Bubble Games on Your Android Device

    -

    Do you love popping bubbles? Do you want to have fun and relax with colorful and addictive bubble games? If you answered yes, then you might want to download bubble APKs on your Android device. Bubble APKs are files that allow you to install and play bubble games that are not available on the Google Play Store. In this article, we will tell you everything you need to know about bubble APKs, including what they are, why you should download them, how to download and install them, and how to play and enjoy them.

    -

    What are Bubble Games?

    -

    Bubble games are a genre of casual games that involve shooting, matching, or popping bubbles of the same color or shape. They are usually simple, easy, and fun to play, but can also be challenging and addictive. Bubble games can be played by anyone, regardless of age or skill level.

    -

    bubble apk download


    Download File ————— https://bltlly.com/2uOk4W



    -

    The History of Bubble Games

    -

    The first bubble game was created in 1986 by a Japanese company called Taito. It was called Puzzle Bobble, also known as Bust-a-Move in North America. It was a two-player arcade game that featured cute dinosaurs shooting bubbles at the top of the screen. The goal was to clear all the bubbles before they reached the bottom. Puzzle Bobble was a huge success and spawned many sequels and spin-offs. It also inspired many other bubble games, such as Bubble Shooter, Bubble Witch Saga, Angry Birds POP, and more.

    -

    The Types of Bubble Games

    -

    There are many types of bubble games available for Android devices. Some of the most popular ones are:

    -
      -
    • Bubble Shooter: This is the classic bubble game that involves shooting bubbles at a cluster of bubbles at the top of the screen. The aim is to match three or more bubbles of the same color to pop them and clear the board. There are many variations of this game, such as Bubble Shooter Classic, Bubble Shooter Legend, and more.
    • -
    • Bubble Pop: This is a type of bubble game that involves tapping or popping bubbles that are floating on the screen. The goal is to pop as many bubbles as possible in a limited time or with a limited number of moves. Some examples of this game are PopStar!, Pop It!, and more.
    • -
    • Bubble Match: This is a type of bubble game that involves swapping or sliding bubbles on a grid to create matches of three or more bubbles of the same color or shape. The objective is to clear all the bubbles from the grid or reach a certain score. Some examples of this game are Candy Crush Saga, Farm Heroes Saga, and more.
    • -
    -

    Why Download Bubble APKs?

    -

    Bubble APKs are files that allow you to install and play bubble games that are not available on the Google Play Store. There are many reasons why you might want to download bubble APKs, such as:

    -

    The Benefits of Bubble APKs

    -
      -
    • You can access more bubble games that are not on the Google Play Store. Some bubble games may be exclusive to certain regions or platforms, or may have been removed from the Google Play Store for various reasons. By downloading bubble APKs, you can enjoy these games on your Android device.
    • -
    • You can play the latest versions of bubble games without waiting for updates. Sometimes, the developers of bubble games may release new features or bug fixes for their games, but they may take some time to update them on the Google Play Store. By downloading bubble APKs, you can get the latest versions of your favorite bubble games as soon as they are available.
    • -
    • You can save storage space on your device . By downloading bubble APKs, you can save storage space on your device by deleting the original apps that you don't need anymore. You can also choose to install only the bubble games that you like, and not download the ones that you don't.
    • -
    • You can customize your bubble games according to your preferences. By downloading bubble APKs, you can modify or tweak some aspects of your bubble games, such as the graphics, the sound, the difficulty, and more. You can also use cheats or hacks to enhance your gaming experience.
    • -
    -

    The Risks of Bubble APKs

    -
      -
    • You may expose your device to malware or viruses. Some bubble APKs may contain malicious code or software that can harm your device or steal your personal information. You should always be careful and download bubble APKs from trusted and reputable sources.
    • -
    • You may violate the terms and conditions of the game developers or the Google Play Store. Some bubble APKs may be illegal or unauthorized copies of the original games, or may contain pirated or copyrighted content. By downloading and using these bubble APKs, you may be infringing on the rights of the game developers or the Google Play Store, and you may face legal consequences or penalties.
    • -
    • You may lose your progress or data in your bubble games. Some bubble APKs may not be compatible with your device or the original games, and they may cause errors or glitches in your bubble games. You may also lose your progress or data in your bubble games if you uninstall them or switch to a different device.
    • -
    -

    How to Download and Install Bubble APKs?

    -

    If you want to download and install bubble APKs on your Android device, you need to follow these steps:

    -

    The Sources of Bubble APKs

    -
      -
    • Find a reliable and trustworthy source of bubble APKs. You can search online for websites or blogs that offer bubble APKs for download. You can also use online forums or social media platforms to ask for recommendations from other users who have downloaded bubble APKs before.
    • -
    • Check the reviews and ratings of the bubble APKs that you want to download. You can read the comments and feedback from other users who have downloaded and used the bubble APKs that you are interested in. You can also look for screenshots or videos of the bubble APKs in action. This will help you to verify the quality and authenticity of the bubble APKs.
    • -
    • Compare the features and specifications of the bubble APKs that you want to download. You can check the size, version, compatibility, and requirements of the bubble APKs that you want to download. You can also compare the features and functions of the bubble APKs with the original games. This will help you to choose the best bubble APK for your device and your gaming needs.
    • -
    -

    The Steps of Downloading and Installing Bubble APKs

    -
      -
    • Enable unknown sources on your device. Before you can install any bubble APK on your device, you need to allow your device to install apps from unknown sources. To do this, go to Settings > Security > Unknown Sources and toggle it on.
    • -
    • Download the bubble APK file on your device. Once you have found a source of bubble APK that you trust, you can download the file on your device. You can use a browser or a downloader app to do this. Make sure that you have enough storage space on your device for the file.
    • -
    • Install the bubble APK file on your device. After you have downloaded the file, you can install it on your device by tapping on it and following the instructions on the screen. You may need to grant some permissions or accept some terms and conditions before you can install it.
    • -
    • Launch and play the bubble game on your device. Once you have installed the bubble APK file on your device, you can launch it from your app drawer or home screen. You can then enjoy playing the bubble game on your device.
    • -
    -

    How to Play and Enjoy Bubble Games?

    -

    Now that you have downloaded and installed bubble APKs on your device, you can play and enjoy them anytime and anywhere. Here are some tips and tricks to help you get the most out of your bubble games:

    -

    The Features of Bubble Games

    -
      -
    • Explore the different modes and levels of your bubble games. Most bubble games have different modes and levels that offer different challenges and rewards. You can try them all and see which ones suit your style and preference.
    • -
    • Use the power-ups and boosters in your bubble games. Most bubble games have power-ups and boosters that can help you clear more bubbles, score more points, or overcome difficult situations. You can use them wisely and strategically to enhance your gameplay.
    • -
    • Connect with other players in your bubble games . Most bubble games have social features that allow you to connect with other players around the world. You can chat, compete, cooperate, or exchange gifts with them. You can also join or create a clan or a team to play with your friends or family.
    • -
    • Collect the rewards and achievements in your bubble games. Most bubble games have rewards and achievements that you can earn by playing the game. You can collect coins, gems, stars, trophies, badges, and more. You can use them to unlock new features, items, or characters in the game.
    • -
    -

    The Tips and Tricks of Bubble Games

    -
      -
    • Aim carefully and strategically. The key to success in bubble games is to aim your bubbles accurately and strategically. You can use the walls or the edges of the screen to bounce your bubbles and reach difficult spots. You can also aim for the clusters of bubbles that have the same color as your bubble, or the bubbles that are holding other bubbles.
    • -
    • Plan ahead and think fast. Another important skill in bubble games is to plan ahead and think fast. You need to anticipate the movement and the position of the bubbles on the screen, and choose the best bubble to shoot. You also need to act quickly and avoid wasting time or moves, as some bubble games have a timer or a limit on how many bubbles you can shoot.
    • -
    • Use the hints and clues in your bubble games. Some bubble games have hints and clues that can help you solve the puzzles or clear the levels. You can use them to find the best angle, the best bubble, or the best strategy to play the game. You can also look for patterns, colors, shapes, or symbols that can give you hints or clues.
    • -
    -

    Conclusion

    -

    Bubble games are a fun and relaxing way to pass the time and enjoy yourself. They are easy to play but hard to master, and they offer a variety of challenges and rewards. By downloading bubble APKs on your Android device, you can access more bubble games that are not on the Google Play Store, and play them with more features and options. However, you should also be aware of the risks and precautions of downloading bubble APKs, and always download them from trusted sources. We hope that this article has helped you learn more about bubble APKs and how to play and enjoy them on your Android device.

    -

    FAQs

    -

    Here are some frequently asked questions about bubble APKs:

    -

    What is an APK?

    -

    An APK is an Android Package Kit, which is a file format that contains all the elements of an Android app. It is used to install apps on Android devices.

    -

    bubble shooter apk download
    -bubble pop apk download
    -bubble witch saga apk download
    -bubble blast apk download
    -bubble trouble apk download
    -bubble bobble apk download
    -bubble island apk download
    -bubble mania apk download
    -bubble breaker apk download
    -bubble worlds apk download
    -bubble safari apk download
    -bubble birds apk download
    -bubble town apk download
    -bubble wrap apk download
    -bubble legend apk download
    -bubble spinner apk download
    -bubble dragon apk download
    -bubble frenzy apk download
    -bubble monkey apk download
    -bubble buster apk download
    -bubble shooter 2 apk download
    -bubble witch 2 saga apk download
    -bubble shooter 3 apk download
    -bubble cloud apk download
    -bubble zoo rescue apk download
    -bubble shooter classic apk download
    -bubble coco apk download
    -bubble shooter deluxe apk download
    -bubble shooter pro apk download
    -bubble shooter 2023 apk download
    -bubble farm apk download
    -bubble shooter adventure apk download
    -bubble shooter galaxy apk download
    -bubble shooter puzzle apk download
    -bubble shooter magic apk download
    -bubble shooter offline apk download
    -bubble shooter free apk download
    -bubble shooter hd apk download
    -bubble shooter candy crush apk download
    -bubble shooter original apk download[^1^] [^2^]

    -

    What is a bubble APK?

    -

    A bubble APK is an APK file that contains a bubble game that is not available on the Google Play Store.

    -

    How do I download a bubble APK?

    -

    You can download a bubble APK from a reliable and trustworthy source online. You can use a browser or a downloader app to do this.

    -

    How do I install a bubble APK?

    -

    You need to enable unknown sources on your device first, then tap on the downloaded file and follow the instructions on the screen.

    -

    How do I play a bubble game?

    -

    You need to launch the app from your app drawer or home screen, then choose a mode or level and start shooting or popping bubbles.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Efootball Pes 2023 PPSSPP for Android and IOS with Mediafire Link Latest Updates and Features.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Efootball Pes 2023 PPSSPP for Android and IOS with Mediafire Link Latest Updates and Features.md deleted file mode 100644 index e560ecdf4a8aef25069a0d77001c7cb5aaa9d480..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Efootball Pes 2023 PPSSPP for Android and IOS with Mediafire Link Latest Updates and Features.md +++ /dev/null @@ -1,163 +0,0 @@ -
    -

    eFootball PES 2023 PPSSPP Download Mediafire: How to Play the Latest Version of PES on Your Mobile Device

    -

    If you are a fan of soccer games, you might have heard of eFootball PES 2023, the latest installment of the popular Pro Evolution Soccer series by Konami. This game offers a realistic and immersive soccer experience, with stunning graphics, smooth gameplay, and various modes and features to enjoy.

    -

    But did you know that you can also play this game on your mobile device using a PSP emulator? Yes, you read that right. You can download eFootball PES 2023 PPSSPP, a modified version of the game that runs on PSP emulators such as PPSSPP, which is available for Android and PC.

    -

    efootball pes 2023 ppsspp download mediafıre


    Download Zip » https://bltlly.com/2uOlQG



    -

    In this article, we will show you how to download and install eFootball PES 2023 PPSSPP from Mediafire, one of the most reliable and fast file-sharing platforms. We will also tell you what are the system requirements for playing this game, what are the gameplay modes and features that you can enjoy, and how to play online with friends or other players. So, without further ado, let's get started!

    -

    What is eFootball PES 2023 PPSSPP?

    -

    A brief introduction to the game and its features

    -

    eFootball PES 2023 PPSSPP is a modified version of eFootball PES 2023, which is designed to run on PSP emulators such as PPSSPP. PSP emulators are software that allow you to play PSP games on your mobile device or PC by simulating the PSP hardware and software.

    -

    eFootball PES 2023 PPSSPP has all the features and content of the original game, such as authentic teams, players, stadiums, kits, leagues, tournaments, etc. It also has some additional features that are exclusive to this version, such as new transfers, kits, faces, graphics, etc.

    -

    Some of the main features of eFootball PES 2023 PPSSPP are:

    -
      -
    • Live Updates: The game data is regularly updated via Live Updates, which reflect the latest changes in real-life soccer events, such as transfers, injuries, form, etc.
    • -
    • National Selection: Every Monday, you can sign players from the national teams that are participating in the International Cup, which is a special mode that simulates the FIFA World Cup.
    • -
    • POTW: Every Thursday, you can sign players who performed well in the previous week's matches, which are called Players of the Week (POTW). These players have boosted stats and skills, and can be a valuable addition to your team.
    • -
    • Epic Players: Every month, you can sign Epic Players, who are legendary players from the past or present, such as Cristiano Ronaldo, Lionel Messi, Diego Maradona, etc. These players have exceptional abilities and can make a difference in any match.
    • -
    • Big Time: Every season, you can sign Big Time players, who are the best players in the world according to their positions, such as Robert Lewandowski, Kevin De Bruyne, Virgil van Dijk, etc. These players have the highest ratings and skills in the game, and can dominate any opponent.
    • -
    -

    How to download and install the game from Mediafire

    -

    To download and install eFootball PES 2023 PPSSPP from Mediafire, you will need to follow these steps:

    -
      -
    1. Download the PPSSPP emulator for your device from the official website. You can choose between the Android or PC version, depending on your device.
    2. -
    3. Download the eFootball PES 2023 PPSSPP ISO file from this link. This is the main game file that contains all the data and content of the game.
    4. -
    5. Download the eFootball PES 2023 PPSSPP Save Data file from this link. This is the file that contains all the updates and modifications of the game, such as new transfers, kits, faces, graphics, etc.
    6. -
    7. Extract the eFootball PES 2023 PPSSPP ISO file and the eFootball PES 2023 PPSSPP Save Data file using a file extractor app such as ZArchiver for Android or WinRAR for PC.
    8. -
    9. Move the extracted eFootball PES 2023 PPSSPP ISO file to the PSP/GAME folder on your device's storage. If you don't have this folder, create it manually.
    10. -
    11. Move the extracted eFootball PES 2023 PPSSPP Save Data file to the PSP/SAVEDATA folder on your device's storage. If you don't have this folder, create it manually.
    12. -
    13. Launch the PPSSPP emulator on your device and locate the eFootball PES 2023 PPSSPP ISO file in the PSP/GAME folder. Tap on it to start playing the game.
    14. -
    -

    Congratulations! You have successfully downloaded and installed eFootball PES 2023 PPSSPP from Mediafire. Enjoy playing the game on your mobile device or PC!

    -

    What are the system requirements for eFootball PES 2023 PPSSPP?

    -

    The minimum and recommended specifications for Android and PC

    -

    To play eFootball PES 2023 PPSSPP smoothly on your device, you will need to meet certain system requirements. Here are the minimum and recommended specifications for Android and PC:

    -

    efootball pes 2023 ppsspp iso file download
    -pes 2023 psp for android and ios free download
    -efootball pes 2023 ppsspp update kits and transfers
    -pes 2023 ppsspp english commentary graphics hd
    -efootball pes 2023 ppsspp android pc game zip
    -pes 2023 ppsspp texture and savedata download
    -efootball pes 2023 ppsspp latest player transfer updates
    -pes 2023 psp camera ps5 mod download
    -efootball pes 2023 ppsspp pro evolution soccer game
    -pes 2023 ppsspp new features and gameplay
    -efootball pes 2023 ppsspp offline mode download
    -pes 2023 psp best settings and controls
    -efootball pes 2023 ppsspp sportsextral.com download link
    -pes 2023 ppsspp thesecondgameerpro.com download page
    -efootball pes 2023 ppsspp 4shared.com free download
    -pes 2023 psp how to install and play guide
    -efootball pes 2023 ppsspp rotech n game free download
    -pes 2023 ppsspp new kits and jerseys update
    -efootball pes 2023 ppsspp high quality graphics and sound
    -pes 2023 psp compatible devices and requirements
    -efootball pes 2023 ppsspp cheats and tips
    -pes 2023 psp review and rating
    -efootball pes 2023 ppsspp apk and obb download
    -pes 2023 psp real teams and players names
    -efootball pes 2023 ppsspp mediafıre direct download link
    -pes 2023 psp online multiplayer mode download
    -efootball pes 2023 ppsspp latest version download
    -pes 2023 psp patch and mod download
    -efootball pes 2023 ppsspp original game download
    -pes 2023 psp best players and teams to use
    -efootball pes 2023 ppsspp emulator download for pc
    -pes 2023 psp license key and activation code
    -efootball pes 2023 ppsspp iso highly compressed download
    -pes 2023 psp new stadiums and leagues update
    -efootball pes 2023 ppsspp no password no verification download
    -pes 2023 psp how to fix errors and bugs
    -efootball pes 2023 ppsspp unlimited money and coins download
    -pes 2023 psp best formation and tactics to use
    -efootball pes 2023 ppsspp official trailer and gameplay video
    -pes 2023 psp how to update to the latest version

    - - - - -
    DeviceMinimum SpecificationsRecommended Specifications
    Android- Android 4.1 or higher
    - 1 GB of RAM
    - 2 GB of free storage space
    - OpenGL ES 2.0 compatible GPU
    - Quad-core processor
    - Android 6.0 or higher
    - 2 GB of RAM or more
    - 4 GB of free storage space
    - OpenGL ES 3.0 compatible GPU
    - Octa-core processor or higher
    PC- Windows 7 or higher
    - 2 GB of RAM
    - 4 GB of free storage space
    - DirectX 9.0c compatible GPU
    - Dual-core processor
    - Windows 10 or higher
    - 4 GB of RAM or more
    - 8 GB of free storage space
    - DirectX 11 compatible GPU
    - Quad-core processor or higher
    -

    How to optimize the game settings for better performance

    -

    If you want to improve the performance and graphics of eFootball PES 2023 PPSSPP on your device, you can tweak some settings in the PPSSPP emulator. Here are some of the settings that you can adjust to optimize the game:

    -
      -
    • Graphics: You can change the rendering resolution, frame rate, texture filtering, texture scaling, and other graphics options to suit your device's capabilities and preferences. For example, you can increase the resolution and frame rate for better clarity and smoothness, or lower them for faster loading and less lag.
    • -
    • Audio: You can enable or disable the sound effects, music, and voice in the game. You can also adjust the volume and latency of the audio. For example, you can disable the audio if you want to save battery or play without headphones, or enable it if you want to enjoy the realistic sounds and commentary of the game.
    • -
    • Controls: You can customize the layout, size, opacity, and sensitivity of the on-screen buttons and analog sticks. You can also use external controllers or keyboards to play the game. For example, you can resize and reposition the buttons to fit your fingers, or use a controller to have a more comfortable and precise control.
    • -
    • Network: You can enable or disable the network features of the game, such as Live Updates, online matches, leaderboards, etc. You can also change the network settings, such as port offset, proxy server, etc. For example, you can enable the network features if you want to play online with other players, or disable them if you want to play offline or save data.
    • -
    -

    To access these settings, you need to tap on the menu icon on the top right corner of the PPSSPP emulator screen, then select Settings. You can then explore and modify the different options under Graphics, Audio, Controls, and Network tabs.

    -

    What are the gameplay modes and features of eFootball PES 2023 PPSSPP?

    -

    The different modes available, such as Trial Match, Tour Event, Challenge Event, and International Cup

    -

    eFootball PES 2023 PPSSPP offers various gameplay modes that you can choose from, depending on your mood and preference. Here are some of the modes that you can play:

    -
      -
    • Trial Match: This is a mode where you can play a single match against a random opponent. You can select your team, difficulty level, match time, stadium, weather, etc. This is a good mode to practice your skills and test your strategies.
    • -
    • Tour Event: This is a mode where you can play a series of matches against different teams from a specific league or region. You can earn rewards such as coins, players, items, etc. by completing objectives and achieving milestones. This is a good mode to build your team and collect more resources.
    • -
    • Challenge Event: This is a mode where you can play a special match with certain conditions and rules. You can face various challenges such as scoring goals with headers, winning by a certain margin, playing with a limited number of players, etc. This is a good mode to challenge yourself and have fun.
    • -
    • International Cup: This is a mode where you can participate in the International Cup tournament, which is based on the FIFA World Cup. You can select your national team and compete against other teams from around the world. You can also sign players from the national teams that are participating in the tournament. This is a good mode to experience the thrill and excitement of the World Cup.
    • -
    -

    The new and updated features, such as Live Updates, National Selection, POTW, Epic Players, and Big Time

    -

    eFootball PES 2023 PPSSPP also has some new and updated features that make the game more realistic and enjoyable. Here are some of the features that you can explore:

    -
      -
    • Live Updates: As mentioned earlier, the game data is regularly updated via Live Updates, which reflect the latest changes in real-life soccer events, such as transfers, injuries, form, etc. This means that you can play with the most accurate and up-to-date rosters, stats, and ratings of the teams and players in the game.
    • -
    • National Selection: Every Monday, you can sign players from the national teams that are participating in the International Cup, which is a special mode that simulates the FIFA World Cup. You can sign up to three players per week, and they will have boosted stats and skills based on their performance in the tournament. You can also use these players in other modes, such as Tour Event and Challenge Event.
    • -
    • POTW: Every Thursday, you can sign players who performed well in the previous week's matches, which are called Players of the Week (POTW). These players have boosted stats and skills based on their performance in real-life matches, and they can be a valuable addition to your team. You can sign up to three players per week, and they will be available for one week only.
    • -
    • Epic Players: Every month, you can sign Epic Players, who are legendary players from the past or present, such as Cristiano Ronaldo, Lionel Messi, Diego Maradona, etc. These players have exceptional abilities and can make a difference in any match. You can sign one player per month, and they will be available for one month only.
    • -
    • Big Time: Every season, you can sign Big Time players, who are the best players in the world according to their positions, such as Robert Lewandowski, Kevin De Bruyne, Virgil van Dijk, etc. These players have the highest ratings and skills in the game, and can dominate any opponent. You can sign one player per season, and they will be available for one season only.
    • -
    -

    How to play eFootball PES 2023 PPSSPP online with friends or other players?

    -

    The steps to set up a multiplayer match using PPSSPP emulator

    -

    If you want to play eFootball PES 2023 PPSSPP online with friends or other players, you will need to use the PPSSPP emulator's network features. Here are the steps to set up a multiplayer match using PPSSPP emulator:

    -
      -
    1. Make sure that you and your friends or other players have the same version of eFootball PES 2023 PPSSPP ISO file and Save Data file on your devices.
    2. -
    3. Make sure that you and your friends or other players are connected to the same Wi-Fi network or hotspot.
    4. -
    5. Launch the PPSSPP emulator on your device and go to Settings > Network.
    6. -
    7. Enable WLAN (Ad hoc) mode and change the MAC address to a random value.
    8. -
    9. Enter a port offset value between 1000 and 65535. Make sure that you and your friends or other players use the same port offset value.
    10. -
    11. Go back to the main menu of the PPSSPP emulator and select eFootball PES 2023 PPSSPP ISO file from the PSP/GAME folder.
    12. -
    13. Select Online Match from the game menu and choose either Host Match or Join Match.
    14. -
    15. If you choose Host Match, you will create a room where other players can join. You can set a password for your room if you want to play with specific players.
    16. -
    17. If you choose Join Match, you will see a list of rooms created by other players. You can join any room that has an open slot or enter a password if required.
    18. -
    19. Once you are in a room with other players, you can select your team, match settings, stadium, etc. and start playing online.
    20. -
    -

    Note: The online match feature of eFootball PES 2023 PPSSPP may not work on some devices or networks due to compatibility issues. If you encounter any problems or errors while playing online, please try changing your network settings or using a different device or network.

    -

    The tips and tricks to improve your skills and tactics in online matches

    -

    Playing eFootball PES 2023 PPSSPP online with friends or other players can be fun and challenging. However, it can also be frustrating if you lose frequently or face stronger opponents. To improve your skills and tactics in online matches, here are some tips and tricks that you can follow:

    -
      -
    • Practice: The best way to improve your skills and tactics in online matches is to practice regularly. You can play Trial Match mode to practice against different opponents and difficulty levels. You can also play Tour Event and Challenge Event modes to earn rewards and improve your team.
    • -
    • Learn: The second best way to improve your skills and tactics in online matches is to learn from others. You can watch online videos or streams of other players who play eFootball PES 2023 PPSSPP online. You can observe their moves, strategies, formations, etc. and try to apply them to your own game.
    • -
    • Adapt: The third best way to improve your skills and tactics in online matches is to adapt to different situations and opponents. You can change your team, formation, tactics, players, etc. according to the match conditions, such as the score, time, weather, etc. You can also adjust your play style according to your opponent's strengths and weaknesses.
    • -
    • Communicate: The fourth best way to improve your skills and tactics in online matches is to communicate with your friends or other players. You can use the chat feature or voice chat feature of the PPSSPP emulator to communicate with your teammates or opponents. You can share tips, feedback, compliments, etc. and have a friendly and respectful conversation.
    • -
    • Enjoy: The fifth best way to improve your skills and tactics in online matches is to enjoy the game. Don't take the game too seriously or get too frustrated or angry if you lose or face difficulties. Remember that it is just a game and the main purpose is to have fun and relax.
    • -
    -

    Conclusion

    -

    A summary of the main points and benefits of playing eFootball PES 2023 PPSSPP

    -

    In conclusion, eFootball PES 2023 PPSSPP is a great game that you can play on your mobile device or PC using a PSP emulator. It has all the features and content of the original game, plus some additional features that are exclusive to this version. It also has various gameplay modes and features that you can enjoy, such as Live Updates, National Selection, POTW, Epic Players, Big Time, etc.

    -

    Playing eFootball PES 2023 PPSSPP online with friends or other players can be fun and challenging. However, it can also be frustrating if you lose frequently or face stronger opponents. To improve your skills and tactics in online matches, you can practice, learn, adapt, communicate, and enjoy the game.

    -

    If you are a fan of soccer games, you should definitely download and install eFootball PES 2023 PPSSPP from Mediafire and play it on your mobile device or PC. It is one of the best soccer games that you can play on any device, with realistic and immersive graphics, gameplay, and features.

    -

    A call to action to download the game and enjoy it

    -

    So what are you waiting for? Download eFootball PES 2023 PPSSPP from Mediafire today and start playing the game on your mobile device or PC. You will not regret it!

    -

    You can download the game files from the links below:

    - -

    You can also watch this video tutorial on how to download and install eFootball PES 2023 PPSSPP from Mediafire:

    - -

    FAQs

    -

    Q1. Is eFootball PES 2023 PPSSPP free to play?

    -

    A1. Yes, eFootball PES 2023 PPSSPP is free to play. You don't need to pay anything to download or play the game. However, you may need to pay for some optional features or items in the game, such as coins, players, items, etc.

    -

    Q2. How often is eFootball PES 2023 PPSSPP updated?

    -

    A2. eFootball PES 2023 PPSSPP is updated regularly via Live Updates, which reflect the latest changes in real-life soccer events, such as transfers, injuries, form, etc. You can also download the latest eFootball PES 2023 PPSSPP Save Data file from Mediafire, which contains all the updates and modifications of the game, such as new transfers, kits, faces, graphics, etc.

    -

    Q3. Can I play eFootball PES 2023 PPSSPP offline?

    -

    A3. Yes, you can play eFootball PES 2023 PPSSPP offline. You don't need an internet connection to play the game, except for downloading the game files and updating the game data via Live Updates. You can play offline modes such as Trial Match, Tour Event, Challenge Event, and International Cup without any problem.

    -

    Q4. How can I get more coins and players in eFootball PES 2023 PPSSPP?

    -

    A4. You can get more coins and players in eFootball PES 2023 PPSSPP by playing the game and completing objectives and milestones. You can also get coins and players by signing National Selection, POTW, Epic Players, and Big Time players every week or month. You can also buy coins and players with real money if you want to.

    -

    Q5. What are the best teams and players in eFootball PES 2023 PPSSPP?

    -

    A5. The best teams and players in eFootball PES 2023 PPSSPP may vary depending on your preference and play style. However, some of the teams and players that are generally considered to be the best are:

    -
      -
    • Teams: Barcelona, Real Madrid, Bayern Munich, Manchester City, Liverpool, Juventus, PSG, etc.
    • -
    • Players: Cristiano Ronaldo, Lionel Messi, Robert Lewandowski, Kevin De Bruyne, Virgil van Dijk, Kylian Mbappe, Neymar Jr., etc.
    • -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/tioseFevbu/cartoon-converter/scripts/Descargar Crack Para Todos Los Juegos De Zylom.md b/spaces/tioseFevbu/cartoon-converter/scripts/Descargar Crack Para Todos Los Juegos De Zylom.md deleted file mode 100644 index 87593994524c6c14b26be1164227f1a39b8c24dc..0000000000000000000000000000000000000000 --- a/spaces/tioseFevbu/cartoon-converter/scripts/Descargar Crack Para Todos Los Juegos De Zylom.md +++ /dev/null @@ -1,19 +0,0 @@ -
    -I can try to write a title and an article with SEO optimization and HTML formatting for the keyword "descargar crack para todos los juegos de zylom". Here is what I came up with: - -

    Descargar crack para todos los juegos de zylom: cómo hacerlo y por qué

    -

    ¿Te gustan los juegos de zylom pero no quieres pagar por ellos? ¿Quieres disfrutar de todos los niveles y modos sin restricciones? Entonces lo que necesitas es descargar crack para todos los juegos de zylom. Un crack es un programa que modifica el código original de un juego para eliminar la protección contra la copia y permitir su uso ilimitado. En este artículo te explicaremos cómo descargar crack para todos los juegos de zylom y por qué hacerlo.

    -

    Cómo descargar crack para todos los juegos de zylom

    -

    Para descargar crack para todos los juegos de zylom, lo primero que tienes que hacer es buscar en internet una página web que ofrezca este tipo de archivos. Hay muchas opciones disponibles, pero debes tener cuidado con las posibles amenazas de virus o malware que puedan infectar tu ordenador. Por eso, te recomendamos que uses un antivirus actualizado y que descargues solo de sitios de confianza.

    -

    descargar crack para todos los juegos de zylom


    Downloadhttps://urlcod.com/2uHyrJ



    -

    Una vez que hayas encontrado una página web que ofrezca crack para todos los juegos de zylom, el siguiente paso es elegir el juego que quieres desbloquear. Normalmente, cada juego tiene su propio crack, así que tendrás que buscar el que corresponda al título que quieres jugar. Asegúrate de que el crack sea compatible con la versión del juego que tienes instalada en tu ordenador.

    -

    Después de elegir el crack, tendrás que descargarlo en tu ordenador. El archivo suele estar comprimido en formato ZIP o RAR, así que tendrás que extraerlo con un programa como WinRAR o 7-Zip. Dentro del archivo comprimido encontrarás el crack, que puede ser un ejecutable o un archivo DLL. También puede haber un archivo de texto con instrucciones sobre cómo usar el crack.

    -

    Para aplicar el crack, tendrás que copiarlo en la carpeta donde está instalado el juego. Normalmente, esta carpeta se encuentra en C:\Archivos de programa\Zylom Games o en C:\Archivos de programa (x86)\Zylom Games, dependiendo de si tu sistema operativo es de 32 o 64 bits. Antes de copiar el crack, te recomendamos que hagas una copia de seguridad del archivo original del juego, por si acaso algo sale mal.

    -

    Una vez que hayas copiado el crack en la carpeta del juego, podrás ejecutarlo y disfrutar de todos los juegos de zylom sin limitaciones. Recuerda que cada vez que quieras jugar tendrás que usar el crack, ya que si usas el acceso directo del juego se activará la protección contra la copia y te pedirá una clave o un código de activación.

    -

    Por qué descargar crack para todos los juegos de zylom

    -

    Descargar crack para todos los juegos de zylom tiene varias ventajas. La principal es que podrás jugar a todos los juegos de zylom gratis, sin tener que pagar nada por ellos. Además, podrás acceder a todos los niveles y modos de juego, sin tener que esperar a desbloquearlos o comprarlos con dinero real. Así podrás disfrutar al máximo de la diversión y el entretenimiento que ofrecen estos juegos.

    -

    Otra ventaja es que podrás jugar sin conexión a internet, lo que te permitirá ahorrar datos y evitar posibles interrupciones o problemas de conexión. También podrás jugar sin publicidad ni anuncios molestos que interrumpan tu experiencia de juego. Y si quieres compartir tus logros o competir con otros jugadores, podrás hacerlo usando programas como Hamachi o Tunngle, que crean redes virtuales privadas entre ordenadores.

    -

    -

    Descargar crack para todos los juegos de zylom también tiene algunos inconvenientes. El principal es que se trata de una práctica ilegal, ya que viola los derechos de autor y las condiciones de uso de los juegos. Esto puede acarrear consecuencias legales tanto para ti como para

    7196e7f11a
    -
    -
    \ No newline at end of file diff --git a/spaces/tioseFevbu/cartoon-converter/scripts/Free Download LINK 3gp Movie Edward Scissorhand In Hindi Dubbed.md b/spaces/tioseFevbu/cartoon-converter/scripts/Free Download LINK 3gp Movie Edward Scissorhand In Hindi Dubbed.md deleted file mode 100644 index fce5f673b5b3eddf901293fcbf91f8e182833475..0000000000000000000000000000000000000000 --- a/spaces/tioseFevbu/cartoon-converter/scripts/Free Download LINK 3gp Movie Edward Scissorhand In Hindi Dubbed.md +++ /dev/null @@ -1,19 +0,0 @@ -
    -

    How to Watch Edward Scissorhands in Hindi for Free

    -

    Edward Scissorhands is a 1990 fantasy romance movie directed by Tim Burton and starring Johnny Depp, Winona Ryder, and Dianne Wiest. The movie tells the story of Edward, an artificial man with scissors for hands, who falls in love with a suburban girl named Kim.

    -

    Free Download 3gp Movie Edward Scissorhand In Hindi Dubbed


    Downloadhttps://urlcod.com/2uHy1P



    -

    If you are a fan of this movie and want to watch it in Hindi, you might be wondering how to do that. Well, there are some ways to watch Edward Scissorhands in Hindi for free online. Here are some of them:

    -
      -
    • Download Edward Scissorhands (1990) Dual Audio (Hindi-English) 480p or 720p WebRip from MoviesMint. This website provides direct download links of Google Drive, One Drive, and Mega for fast and secure downloading. You can choose the quality and format of the movie according to your preference. The movie has English subtitles as well. You can download the movie from this link: https://moviesmint1.co/download-edward-scissorhands-1990-dual-audio-hindi-english-480p-720p-webrip/
    • -
    • Download Edward Scissorhands (1990) BluRay 480p or 720p HD Movie from Mkvking. This website also provides direct download links of GoogleDrive, Mega, Uptobox, and 1fichier for easy and fast downloading. The movie has dual audio (Hindi and English) and English subtitles as well. You can download the movie from this link: https://84.46.254.230/edward-scissorhands-1990/
    • -
    • Watch Edward Scissorhands (1990) online on streaming platforms that have Hindi dubbed versions of the movie. Some of these platforms are Netflix, Amazon Prime Video, Disney+ Hotstar, and SonyLIV. However, you might need to have a subscription or a free trial to access these platforms. You can also use VPN services to change your location and access geo-restricted content.
    • -
    -

    These are some of the ways to watch Edward Scissorhands in Hindi for free online. We hope you enjoy this classic movie in your preferred language.

    - -

    Edward Scissorhands is not only a movie about a man with scissors for hands, but also a movie about love, acceptance, and creativity. Edward is a gentle and artistic soul who can create amazing sculptures with his hands, but he also faces rejection and fear from the people who don't understand him. He finds a friend in the Avon lady, a mother figure in her husband, and a lover in her daughter, but he also has to deal with the jealousy of her boyfriend, the gossip of the neighbors, and the cruelty of the society.

    -

    -

    The movie is a modern fairy tale with gothic overtones and a sweet center. It has a whimsical and whimsical style that contrasts with the bland and conformist suburbia. The movie also has a dark and tragic side that shows the consequences of intolerance and violence. The movie explores themes such as identity, belonging, loneliness, and beauty. It also shows how Edward's hands are both a gift and a curse, a source of wonder and pain.

    -

    The movie is a showcase of Tim Burton's visual imagination and Johnny Depp's acting talent. Burton creates a stunning and surreal world that mixes fantasy and reality, while Depp gives a touching and nuanced performance as Edward. The movie also features great performances from Winona Ryder, Dianne Wiest, Alan Arkin, and Vincent Price in his last role. The movie also has a beautiful musical score by Danny Elfman that enhances the mood and emotion of the story.

    -

    Edward Scissorhands is a classic movie that has inspired many people and influenced many artists. It is a movie that celebrates difference and diversity, and challenges us to look beyond appearances and stereotypes. It is a movie that reminds us of the power of love and compassion, and the importance of being true to ourselves.

    7b8c122e87
    -
    -
    \ No newline at end of file diff --git a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/setuptools/_vendor/importlib_metadata/_text.py b/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/setuptools/_vendor/importlib_metadata/_text.py deleted file mode 100644 index c88cfbb2349c6401336bc5ba6623f51afd1eb59d..0000000000000000000000000000000000000000 --- a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/setuptools/_vendor/importlib_metadata/_text.py +++ /dev/null @@ -1,99 +0,0 @@ -import re - -from ._functools import method_cache - - -# from jaraco.text 3.5 -class FoldedCase(str): - """ - A case insensitive string class; behaves just like str - except compares equal when the only variation is case. - - >>> s = FoldedCase('hello world') - - >>> s == 'Hello World' - True - - >>> 'Hello World' == s - True - - >>> s != 'Hello World' - False - - >>> s.index('O') - 4 - - >>> s.split('O') - ['hell', ' w', 'rld'] - - >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) - ['alpha', 'Beta', 'GAMMA'] - - Sequence membership is straightforward. - - >>> "Hello World" in [s] - True - >>> s in ["Hello World"] - True - - You may test for set inclusion, but candidate and elements - must both be folded. - - >>> FoldedCase("Hello World") in {s} - True - >>> s in {FoldedCase("Hello World")} - True - - String inclusion works as long as the FoldedCase object - is on the right. - - >>> "hello" in FoldedCase("Hello World") - True - - But not if the FoldedCase object is on the left: - - >>> FoldedCase('hello') in 'Hello World' - False - - In that case, use in_: - - >>> FoldedCase('hello').in_('Hello World') - True - - >>> FoldedCase('hello') > FoldedCase('Hello') - False - """ - - def __lt__(self, other): - return self.lower() < other.lower() - - def __gt__(self, other): - return self.lower() > other.lower() - - def __eq__(self, other): - return self.lower() == other.lower() - - def __ne__(self, other): - return self.lower() != other.lower() - - def __hash__(self): - return hash(self.lower()) - - def __contains__(self, other): - return super().lower().__contains__(other.lower()) - - def in_(self, other): - "Does self appear in other?" - return self in FoldedCase(other) - - # cache lower since it's likely to be called frequently. - @method_cache - def lower(self): - return super().lower() - - def index(self, sub): - return self.lower().index(sub.lower()) - - def split(self, splitter=' ', maxsplit=0): - pattern = re.compile(re.escape(splitter), re.I) - return pattern.split(self, maxsplit) diff --git a/spaces/tobiascz/SDSdemo/runSDSdemo.py b/spaces/tobiascz/SDSdemo/runSDSdemo.py deleted file mode 100644 index 85e2acc1f766d3d53761bf5d3aa8841a13c65d99..0000000000000000000000000000000000000000 --- a/spaces/tobiascz/SDSdemo/runSDSdemo.py +++ /dev/null @@ -1,106 +0,0 @@ -# import pytorch related dependencies -import torch -from PIL import Image -from torch import nn -import numpy as np -import torchvision as torchvision -import torchvision.transforms as transforms -from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, FullGrad -from pytorch_grad_cam.utils.image import show_cam_on_image -import gradio as gr -import timm - -# model setup -device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') -classes = ["Preparation", - "CalotTriangleDissection", - "ClippingCutting", - "GallbladderDissection", - "GallbladderPackaging", - "CleaningCoagulation", - "GallbladderRetraction"] - - -model = timm.create_model('efficientnet_b3')# This is a very well known network but it is designed for 1000 classes and not just cats and dogs this is why we need the next line -model.classifier = nn.Linear(1536, 7) -#state_dict_trained = torch.hub.load_state_dict_from_url("https://github.com/tobiascz/demotime/raw/main/checkpoints/ham10k_checkpoint_mobile_0.82_epoch24.pt", model_dir=".", map_location = device) -import os -print(os.getcwd()) -state_dict_trained = torch.load('checkpoints/state_dict_timm_effnet_b3_e6_val_f1=0.75.pt', map_location=torch.device(device)) -sd = model.state_dict() - -print(state_dict_trained.keys()) - -for k,v in sd.items(): - if not "classifier" in k: - sd[k] = state_dict_trained[f'model.model.{k}'] -sd['classifier.weight'] = state_dict_trained['model.fc_phase.weight'] -sd['classifier.bias'] = state_dict_trained['model.fc_phase.bias'] - -model.load_state_dict(sd) ## Here we load the trained weights (state_dict) in our model -model.eval() # This - -# image pre-processing -norm_mean = (0.4914, 0.4822, 0.4465) -norm_std = (0.2023, 0.1994, 0.2010) -transform = transforms.Compose([ # resize image to the network input size - transforms.CenterCrop((400,400)), - transforms.ToTensor(), - transforms.Normalize(norm_mean, norm_std) - ]) -# convert tensot to numpy array -def tensor2npimg(tensor, mean, std): - # inverse of normalization - tensor = tensor.clone() - mean_tensor = torch.as_tensor(list(mean), dtype=tensor.dtype, device=tensor.device).view(-1,1,1) - std_tensor = torch.as_tensor(list(std), dtype=tensor.dtype, device=tensor.device).view(-1,1,1) - tensor.mul_(std_tensor).add_(mean_tensor) - # convert tensor to numpy format for plt presentation - npimg = tensor.numpy() - npimg = np.transpose(npimg,(1,2,0)) # C*H*W => H*W*C - return npimg - - -# draw Grad-CAM on image -# target layer could be any layer before the final attention block -# Some common choices are: -# FasterRCNN: model.backbone -# Resnet18 and 50: model.layer4[-1] -# VGG and densenet161: model.features[-1] -# mnasnet1_0: model.layers[-1] -# ViT: model.blocks[-1].norm1 -# SwinT: model.layers[-1].blocks[-1].norm1 -def image_grad_cam(model, input_tensor, input_float_np, target_layers): - cam = GradCAM(model=model, target_layers=target_layers, use_cuda=False) - grayscale_cam = cam(input_tensor=input_tensor, aug_smooth=True, eigen_smooth=True) - grayscale_cam = grayscale_cam[0, :] - return show_cam_on_image(input_float_np, grayscale_cam, use_rgb=True) - - -# config the predict function for Gradio, input type of image is numpy.nparray -def predict(input_img): - # numpy.nparray -> PIL.Image - leasionExample = Image.fromarray(input_img.astype('uint8'), 'RGB') - # normalize the image to fit the input size of our model - leasion_tensor = transform(leasionExample) - input_float_np = tensor2npimg(leasion_tensor, norm_mean, norm_std) - leasion_tensor = leasion_tensor.unsqueeze(dim=0) - # predict - with torch.no_grad(): - outputs = model(leasion_tensor) - outputs = torch.exp(outputs) - # probabilities of all classes - pred_softmax = torch.softmax(outputs, dim=1).cpu().numpy()[0] - # class with hightest probability - # diagnostic suggestions - # return label dict and suggestion - return {classes[i]: float(pred_softmax[i]) for i in range(len(classes))} - -# start gradio application -gr.Interface( - fn=predict, - inputs=gr.inputs.Image(), - outputs=[gr.outputs.Label(label="Predict Result")], - examples=[['images/video01_000014_prep.png'],['images/video01_001403.png'],['images/video01_001528_pack.png']], - title="Surgical Workflow Classifier" - ).launch() \ No newline at end of file diff --git a/spaces/tomofi/MMOCR/mmocr/models/textrecog/necks/__init__.py b/spaces/tomofi/MMOCR/mmocr/models/textrecog/necks/__init__.py deleted file mode 100644 index 81a5714481121cf1dd0c8fef480d1785f381f1f1..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/models/textrecog/necks/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .fpn_ocr import FPNOCR - -__all__ = ['FPNOCR'] diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/lvis/mask_rcnn_x101_32x4d_fpn_sample1e-3_mstrain_1x_lvis_v1.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/lvis/mask_rcnn_x101_32x4d_fpn_sample1e-3_mstrain_1x_lvis_v1.py deleted file mode 100644 index 5abcc2e014fe57b862422fa2fe18dd651761b56e..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/lvis/mask_rcnn_x101_32x4d_fpn_sample1e-3_mstrain_1x_lvis_v1.py +++ /dev/null @@ -1,13 +0,0 @@ -_base_ = './mask_rcnn_r50_fpn_sample1e-3_mstrain_1x_lvis_v1.py' -model = dict( - pretrained='open-mmlab://resnext101_32x4d', - backbone=dict( - type='ResNeXt', - depth=101, - groups=32, - base_width=4, - num_stages=4, - out_indices=(0, 1, 2, 3), - frozen_stages=1, - norm_cfg=dict(type='BN', requires_grad=True), - style='pytorch')) diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/ndl/ndl_instance_1024.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/ndl/ndl_instance_1024.py deleted file mode 100644 index cbb62082918878aca4b15d1850328263f801f8d8..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/configs/ndl/ndl_instance_1024.py +++ /dev/null @@ -1,66 +0,0 @@ -dataset_type = 'CocoDataset' -classes = ('line_main', 'line_none', 'line_inote', 'line_hnote', 'line_caption', - 'block_fig', 'block_table', 'block_pillar', 'block_folio', 'block_rubi', - 'block_chart', 'block_eqn', 'block_cfm', 'block_eng', - 'char', 'void') - - -data_root = 'data/coco/' -img_norm_cfg = dict( - mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) - -image_size = 1024 - -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations', with_bbox=True, with_mask=True), - dict(type='Resize', img_scale=(image_size, image_size), keep_ratio=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='DefaultFormatBundle'), - dict(type='Collect', - keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(image_size, image_size), - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] - -data = dict( - samples_per_gpu=1, - workers_per_gpu=1, - train=dict( - type=dataset_type, - # explicitly add your class names to the field `classes` - classes=classes, - ann_file='/tmp/generated/dataset_kindai_preprocessed_train.json', - img_prefix='/tmp/dataset_kindai_preprocessed_out', - pipeline=train_pipeline), - val=dict( - type=dataset_type, - # explicitly add your class names to the field `classes` - classes=classes, - ann_file='/tmp/generated/dataset_kindai_preprocessed_test.json', - img_prefix='/tmp/dataset_kindai_preprocessed_out', - pipeline=test_pipeline), - test=dict( - type=dataset_type, - # explicitly add your class names to the field `classes` - classes=classes, - ann_file='/tmp/generated/dataset_kindai_preprocessed_test.json', - img_prefix='/tmp/dataset_kindai_preprocessed_out', - pipeline=test_pipeline)) - -evaluation = dict(interval=10, metric=['bbox', 'segm'], classwise=True) diff --git a/spaces/tornadoslims/instruct-pix2pix/stable_diffusion/ldm/modules/diffusionmodules/__init__.py b/spaces/tornadoslims/instruct-pix2pix/stable_diffusion/ldm/modules/diffusionmodules/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/training-transformers-together/Dashboard/streamlit_observable/frontend/src/Observable.tsx b/spaces/training-transformers-together/Dashboard/streamlit_observable/frontend/src/Observable.tsx deleted file mode 100644 index f90267fc0c1597f858c36aea88c01269230c8dab..0000000000000000000000000000000000000000 --- a/spaces/training-transformers-together/Dashboard/streamlit_observable/frontend/src/Observable.tsx +++ /dev/null @@ -1,161 +0,0 @@ -import React, { ReactNode } from "react" -import { - withStreamlitConnection, - StreamlitComponentBase, - Streamlit, -} from "./streamlit" -import { Runtime, Inspector } from "@observablehq/runtime"; - -class Observable extends StreamlitComponentBase<{}> { - public observeValue = {}; - private notebookRef = React.createRef(); - private runtime: any = null; - private main: any = null; - - componentWillUnmount() { - this.runtime?.dispose(); - } - // @ts-ignore - public componentDidUpdate(prevProps: any) { - const { args: prevArgs } = prevProps; - if (prevArgs.notebook !== this.props.args.notebook) { - // TODO handle new notebook - } - console.log('this.props.args.redefine: ', this.props.args.redefine); - if (this.main !== null) { - this.redefineCells(this.main, this.props.args.redefine); - } - } - - async embedNotebook(notebook: string, targets: string[], observe: string[], hide:string[]) { - if (this.runtime) { - this.runtime.dispose(); - } - - console.log('Console says hi!'); - - const targetSet = new Set(targets); - const observeSet = new Set(observe); - const hideSet = new Set(hide); - this.runtime = new Runtime(); - const { default: define } = await eval(`import("https://api.observablehq.com/${notebook}.js?v=3")`); - - this.main = this.runtime.module(define, (name: string) => { - console.log('name: ', name); - console.log('observeSet.has(name: ', observeSet.has(name)); - console.log('targetSet.has(name): ', targetSet.has(name)); - if (observeSet.has(name) && !targetSet.has(name)) { - const observeValue = this.observeValue; - - console.log('observeValue: ', observeValue); - - return { - fulfilled: (value: any) => { - //@ts-ignore - observeValue[name] = value; - //@ts-ignore - Streamlit.setComponentValue(observeValue); - } - } - } - if (targetSet.size > 0 && !targetSet.has(name)) return; - if(hideSet.has(name)) return true; - const el = document.createElement('div'); - this.notebookRef.current?.appendChild(el); - - const i = new Inspector(el); - el.addEventListener('input', e => { - Streamlit.setFrameHeight(); - }) - return { - pending() { - i.pending(); - Streamlit.setFrameHeight(); - }, - fulfilled(value: any) { - i.fulfilled(value); - Streamlit.setFrameHeight(); - }, - rejected(error: any) { - i.rejected(error); - Streamlit.setFrameHeight(); - }, - }; - }); - if (observeSet.size > 0) { - Promise.all(Array.from(observeSet).map(async name => [name, await this.main.value(name)])).then(initial => { - for (const [name, value] of initial) { - // @ts-ignore - this.observeValue[name] = value - }; - Streamlit.setComponentValue(this.observeValue); - }) - } - } - - redefineCells(main: any, redefine = {}) { - - console.log('Console says hi 2 !'); - - for (let cell in redefine) { - //@ts-ignore - main.redefine(cell, redefine[cell]); - } - } - componentDidMount() { - const { notebook, targets = [], observe = [], redefine = {} , hide=[]} = this.props.args; - Streamlit.setComponentValue(this.observeValue); - this.embedNotebook(notebook, targets, observe, hide).then(() => { - this.redefineCells(this.main, redefine); - }); - - } - - public render = (): ReactNode => { - - console.log('this.props.args.render_empty: ', this.props.args.render_empty); - if (this.props.args.render_empty) { - return ( -
    -
    -
    -
    -
    - -
    -
    {this.props.args.name}
    -
    - -
    -
    -
    -
    - ) - } - return ( -
    -
    -
    -
    -
    - -
    -
    {this.props.args.name}
    -
    - -
    -
    -
    -
    - ) - } -} - -export default withStreamlitConnection(Observable) diff --git a/spaces/trysem/image-matting-app/ppmatting/models/layers/__init__.py b/spaces/trysem/image-matting-app/ppmatting/models/layers/__init__.py deleted file mode 100644 index 31eba2cacd64eddaf0734495b5a992a86b7bad37..0000000000000000000000000000000000000000 --- a/spaces/trysem/image-matting-app/ppmatting/models/layers/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .gca_module import GuidedCxtAtten diff --git a/spaces/tsi-org/LLaVA/llava/eval/eval_science_qa.py b/spaces/tsi-org/LLaVA/llava/eval/eval_science_qa.py deleted file mode 100644 index e1b3ce52fd6d922f247cc0c48409e88d5af3f204..0000000000000000000000000000000000000000 --- a/spaces/tsi-org/LLaVA/llava/eval/eval_science_qa.py +++ /dev/null @@ -1,99 +0,0 @@ -import argparse -import json -import os -import re -import random - - -def get_args(): - parser = argparse.ArgumentParser() - parser.add_argument('--base-dir', type=str) - parser.add_argument('--result-file', type=str) - parser.add_argument('--output-file', type=str) - parser.add_argument('--output-result', type=str) - parser.add_argument('--split', type=str, default='test') - parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) - return parser.parse_args() - - -def convert_caps(results): - fakecaps = [] - for result in results: - image_id = result['question_id'] - caption = result['text'] - fakecaps.append({"image_id": int(image_id), "caption": caption}) - return fakecaps - - -def get_pred_idx(prediction, choices, options): - """ - Get the index (e.g. 2) from the prediction (e.g. 'C') - """ - if prediction in options[:len(choices)]: - return options.index(prediction) - else: - return random.choice(range(len(choices))) - - -if __name__ == "__main__": - args = get_args() - - base_dir = args.base_dir - split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] - problems = json.load(open(os.path.join(base_dir, "problems.json"))) - predictions = [json.loads(line) for line in open(args.result_file)] - predictions = {pred['question_id']: pred for pred in predictions} - split_problems = {idx: problems[idx] for idx in split_indices} - - results = {'correct': [], 'incorrect': []} - sqa_results = {} - sqa_results['acc'] = None - sqa_results['correct'] = None - sqa_results['count'] = None - sqa_results['results'] = {} - sqa_results['outputs'] = {} - - for prob_id, prob in split_problems.items(): - if prob_id not in predictions: - continue - pred = predictions[prob_id] - pred_text = pred['text'] - - pattern = re.compile(r'The answer is ([A-Z]).') - res = pattern.findall(pred_text) - if len(res) == 1: - answer = res[0] # 'A', 'B', ... - else: - answer = "FAILED" - - pred_idx = get_pred_idx(answer, prob['choices'], args.options) - - analysis = { - 'question_id': prob_id, - 'parsed_ans': answer, - 'ground_truth': args.options[prob['answer']], - 'question': pred['prompt'], - 'pred': pred_text, - 'is_multimodal': '' in pred['prompt'], - } - - sqa_results['results'][prob_id] = get_pred_idx(answer, prob['choices'], args.options) - sqa_results['outputs'][prob_id] = pred_text - - if pred_idx == prob['answer']: - results['correct'].append(analysis) - else: - results['incorrect'].append(analysis) - - correct = len(results['correct']) - total = len(results['correct']) + len(results['incorrect']) - print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%') - - sqa_results['acc'] = correct / total * 100 - sqa_results['correct'] = correct - sqa_results['count'] = total - - with open(args.output_file, 'w') as f: - json.dump(results, f, indent=2) - with open(args.output_result, 'w') as f: - json.dump(sqa_results, f, indent=2) diff --git a/spaces/tsi-org/LLaVA/llava/eval/eval_science_qa_gpt4.py b/spaces/tsi-org/LLaVA/llava/eval/eval_science_qa_gpt4.py deleted file mode 100644 index c2ff17c915481fb556aba6ec816a9e08f519c515..0000000000000000000000000000000000000000 --- a/spaces/tsi-org/LLaVA/llava/eval/eval_science_qa_gpt4.py +++ /dev/null @@ -1,104 +0,0 @@ -import argparse -import json -import os -import re -import random -from collections import defaultdict - - -def get_args(): - parser = argparse.ArgumentParser() - parser.add_argument('--base-dir', type=str) - parser.add_argument('--gpt4-result', type=str) - parser.add_argument('--our-result', type=str) - parser.add_argument('--split', type=str, default='test') - parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"]) - return parser.parse_args() - - -def convert_caps(results): - fakecaps = [] - for result in results: - image_id = result['question_id'] - caption = result['text'] - fakecaps.append({"image_id": int(image_id), "caption": caption}) - return fakecaps - - -def get_pred_idx(prediction, choices, options): - """ - Get the index (e.g. 2) from the prediction (e.g. 'C') - """ - if prediction in options[:len(choices)]: - return options.index(prediction) - else: - return random.choice(range(len(choices))) - - -if __name__ == "__main__": - args = get_args() - - base_dir = args.base_dir - split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split] - problems = json.load(open(os.path.join(base_dir, "problems.json"))) - our_predictions = [json.loads(line) for line in open(args.our_result)] - our_predictions = {pred['question_id']: pred for pred in our_predictions} - split_problems = {idx: problems[idx] for idx in split_indices} - - gpt4_predictions = json.load(open(args.gpt4_result))['outputs'] - - results = defaultdict(lambda: 0) - - for prob_id, prob in split_problems.items(): - if prob_id not in our_predictions: - continue - if prob_id not in gpt4_predictions: - continue - our_pred = our_predictions[prob_id]['text'] - gpt4_pred = gpt4_predictions[prob_id] - - pattern = re.compile(r'The answer is ([A-Z]).') - our_res = pattern.findall(our_pred) - if len(our_res) == 1: - our_answer = our_res[0] # 'A', 'B', ... - else: - our_answer = "FAILED" - gpt4_res = pattern.findall(gpt4_pred) - if len(gpt4_res) == 1: - gpt4_answer = gpt4_res[0] # 'A', 'B', ... - else: - gpt4_answer = "FAILED" - - our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options) - gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options) - - if gpt4_answer == 'FAILED': - results['gpt4_failed'] += 1 - # continue - gpt4_pred_idx = our_pred_idx - # if our_pred_idx != prob['answer']: - # print(our_predictions[prob_id]['prompt']) - # print('-----------------') - # print(f'LECTURE: {prob["lecture"]}') - # print(f'SOLUTION: {prob["solution"]}') - # print('=====================') - else: - # continue - pass - # gpt4_pred_idx = our_pred_idx - - if gpt4_pred_idx == prob['answer']: - results['correct'] += 1 - else: - results['incorrect'] += 1 - - - if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']: - results['correct_upperbound'] += 1 - - correct = results['correct'] - total = results['correct'] + results['incorrect'] - print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%') - print(f'Total: {total}, Correct (upper): {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%') - print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%') - diff --git a/spaces/ttt246/brain/Android/gradlew.bat b/spaces/ttt246/brain/Android/gradlew.bat deleted file mode 100644 index 107acd32c4e687021ef32db511e8a206129b88ec..0000000000000000000000000000000000000000 --- a/spaces/ttt246/brain/Android/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/spaces/unik-style/unik-ml/README.md b/spaces/unik-style/unik-ml/README.md deleted file mode 100644 index f5eb8004733003b5799ffb691a06b0f9d1a091bd..0000000000000000000000000000000000000000 --- a/spaces/unik-style/unik-ml/README.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: FastApi Stable Diffusion Xl Refiner 1.0 - -emoji: 📈 - -colorFrom: pink - -colorTo: gray - -sdk: docker - -python_version: 3.9 - -suggested_hardware: a10g-small - -pinned: false - -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/usbethFlerru/sovits-modelsV2/example/Bs 6399 Part 3 Pdf Free 38 TOP.md b/spaces/usbethFlerru/sovits-modelsV2/example/Bs 6399 Part 3 Pdf Free 38 TOP.md deleted file mode 100644 index 5d58f4a23e82128f98941521ed4dd3602058bccf..0000000000000000000000000000000000000000 --- a/spaces/usbethFlerru/sovits-modelsV2/example/Bs 6399 Part 3 Pdf Free 38 TOP.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Bs 6399 Part 3 Pdf Free 38


    DOWNLOADhttps://urlcod.com/2uyXk1



    -
    -Roof structure. The roof structure is not designed to resist crushing loads. It is designed to resist wind loading and to resist falling loads for brief periods, and snow loading for brief periods. The roof structure shall be constructed of load-bearing elements and may be self-supporting, either by spreading the load over the area of the building or over a scaffolding structure supported by structural columns or anchorage points. An inspection of any building roof shall be made by an inspector in order to ascertain whether its roof structure is in a safe condition to support the roof loads specified in BS 6399 Part 3 Section 2. Bs 6399 Part 3 Section 2 The roof structure shall be such that the combined effect of wind, snow, rainfall and hail shall not cause the collapse of any part of the roof. The protection against a collapse of a part of the roof shall be provided by the anchorage points as specified in BS 6399 Part 3 Section 3. Bs 6399 Part 3 Section 3 iv ii blank A load-bearing member shall be free to move in all directions relative to the structure it is part of. It shall be so constructed that failure of the structure by any of the causes specified in BS 6399 Part 3 Section 1, 2, or 3 shall cause the load-bearing member to fail at that part of the member where the failure occurs. A load-bearing member shall not have any sharp edges or corners. Load-bearing members shall be constructed of load-bearing material and shall have adequate anchorages. Load-bearing members shall be so designed that they will not act as a lever against a structural member which supports them. iv iii blank The load-bearing members shall not give way when subjected to a bending stress in the longitudinal or transverse direction. If a member is designed to resist both longitudinal and transverse loads, this shall not necessarily be so for a load-bearing member. Load-bearing members shall be of sufficient strength to give the required resistance to all loads to which they may be subjected. v iv blank Any part of a load-bearing member which has the tendency to fracture or to loosen shall be so designed as to prevent the fracture or loosening. vii blank The roof structure shall not be subjected to the following forces without adequate reinforcement, whichever is the limiting factor, and the structure shall be so designed and constructed as to withstand these forces: (a) The total load due to the weight of the roof structure itself acting on the roof structure; (b) The total load due to the weight of water supported 4fefd39f24
    -
    -
    -

    diff --git a/spaces/vaibhavarduino/anime-plus/e4e/training/__init__.py b/spaces/vaibhavarduino/anime-plus/e4e/training/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/videfikri/aicover/infer_pack/modules.py b/spaces/videfikri/aicover/infer_pack/modules.py deleted file mode 100644 index 960481cedad9a6106f2bf0b9e86e82b120f7b33f..0000000000000000000000000000000000000000 --- a/spaces/videfikri/aicover/infer_pack/modules.py +++ /dev/null @@ -1,522 +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 - -from infer_pack import commons -from infer_pack.commons import init_weights, get_padding -from 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/vinay123/panoptic-segment-anything/GroundingDINO/groundingdino/models/GroundingDINO/transformer.py b/spaces/vinay123/panoptic-segment-anything/GroundingDINO/groundingdino/models/GroundingDINO/transformer.py deleted file mode 100644 index fcb8742dbdde6e80fd38b11d064211f6935aae76..0000000000000000000000000000000000000000 --- a/spaces/vinay123/panoptic-segment-anything/GroundingDINO/groundingdino/models/GroundingDINO/transformer.py +++ /dev/null @@ -1,959 +0,0 @@ -# ------------------------------------------------------------------------ -# Grounding DINO -# url: https://github.com/IDEA-Research/GroundingDINO -# Copyright (c) 2023 IDEA. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 [see LICENSE for details] -# ------------------------------------------------------------------------ -# DINO -# Copyright (c) 2022 IDEA. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 [see LICENSE for details] -# ------------------------------------------------------------------------ -# Conditional DETR Transformer class. -# Copyright (c) 2021 Microsoft. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 [see LICENSE for details] -# ------------------------------------------------------------------------ -# Modified from DETR (https://github.com/facebookresearch/detr) -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -# ------------------------------------------------------------------------ - -from typing import Optional - -import torch -import torch.utils.checkpoint as checkpoint -from torch import Tensor, nn - -from groundingdino.util.misc import inverse_sigmoid - -from .fuse_modules import BiAttentionBlock -from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn -from .transformer_vanilla import TransformerEncoderLayer -from .utils import ( - MLP, - _get_activation_fn, - _get_clones, - gen_encoder_output_proposals, - gen_sineembed_for_position, - get_sine_pos_embed, -) - - -class Transformer(nn.Module): - def __init__( - self, - d_model=256, - nhead=8, - num_queries=300, - num_encoder_layers=6, - num_unicoder_layers=0, - num_decoder_layers=6, - dim_feedforward=2048, - dropout=0.0, - activation="relu", - normalize_before=False, - return_intermediate_dec=False, - query_dim=4, - num_patterns=0, - # for deformable encoder - num_feature_levels=1, - enc_n_points=4, - dec_n_points=4, - # init query - learnable_tgt_init=False, - # two stage - two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1'] - embed_init_tgt=False, - # for text - use_text_enhancer=False, - use_fusion_layer=False, - use_checkpoint=False, - use_transformer_ckpt=False, - use_text_cross_attention=False, - text_dropout=0.1, - fusion_dropout=0.1, - fusion_droppath=0.0, - ): - super().__init__() - self.num_feature_levels = num_feature_levels - self.num_encoder_layers = num_encoder_layers - self.num_unicoder_layers = num_unicoder_layers - self.num_decoder_layers = num_decoder_layers - self.num_queries = num_queries - assert query_dim == 4 - - # choose encoder layer type - encoder_layer = DeformableTransformerEncoderLayer( - d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points - ) - - if use_text_enhancer: - text_enhance_layer = TransformerEncoderLayer( - d_model=d_model, - nhead=nhead // 2, - dim_feedforward=dim_feedforward // 2, - dropout=text_dropout, - ) - else: - text_enhance_layer = None - - if use_fusion_layer: - feature_fusion_layer = BiAttentionBlock( - v_dim=d_model, - l_dim=d_model, - embed_dim=dim_feedforward // 2, - num_heads=nhead // 2, - dropout=fusion_dropout, - drop_path=fusion_droppath, - ) - else: - feature_fusion_layer = None - - encoder_norm = nn.LayerNorm(d_model) if normalize_before else None - assert encoder_norm is None - self.encoder = TransformerEncoder( - encoder_layer, - num_encoder_layers, - d_model=d_model, - num_queries=num_queries, - text_enhance_layer=text_enhance_layer, - feature_fusion_layer=feature_fusion_layer, - use_checkpoint=use_checkpoint, - use_transformer_ckpt=use_transformer_ckpt, - ) - - # choose decoder layer type - decoder_layer = DeformableTransformerDecoderLayer( - d_model, - dim_feedforward, - dropout, - activation, - num_feature_levels, - nhead, - dec_n_points, - use_text_cross_attention=use_text_cross_attention, - ) - - decoder_norm = nn.LayerNorm(d_model) - self.decoder = TransformerDecoder( - decoder_layer, - num_decoder_layers, - decoder_norm, - return_intermediate=return_intermediate_dec, - d_model=d_model, - query_dim=query_dim, - num_feature_levels=num_feature_levels, - ) - - self.d_model = d_model - self.nhead = nhead - self.dec_layers = num_decoder_layers - self.num_queries = num_queries # useful for single stage model only - self.num_patterns = num_patterns - if not isinstance(num_patterns, int): - Warning("num_patterns should be int but {}".format(type(num_patterns))) - self.num_patterns = 0 - - if num_feature_levels > 1: - if self.num_encoder_layers > 0: - self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model)) - else: - self.level_embed = None - - self.learnable_tgt_init = learnable_tgt_init - assert learnable_tgt_init, "why not learnable_tgt_init" - self.embed_init_tgt = embed_init_tgt - if (two_stage_type != "no" and embed_init_tgt) or (two_stage_type == "no"): - self.tgt_embed = nn.Embedding(self.num_queries, d_model) - nn.init.normal_(self.tgt_embed.weight.data) - else: - self.tgt_embed = None - - # for two stage - self.two_stage_type = two_stage_type - assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format( - two_stage_type - ) - if two_stage_type == "standard": - # anchor selection at the output of encoder - self.enc_output = nn.Linear(d_model, d_model) - self.enc_output_norm = nn.LayerNorm(d_model) - self.two_stage_wh_embedding = None - - if two_stage_type == "no": - self.init_ref_points(num_queries) # init self.refpoint_embed - - self.enc_out_class_embed = None - self.enc_out_bbox_embed = None - - self._reset_parameters() - - def _reset_parameters(self): - for p in self.parameters(): - if p.dim() > 1: - nn.init.xavier_uniform_(p) - for m in self.modules(): - if isinstance(m, MSDeformAttn): - m._reset_parameters() - if self.num_feature_levels > 1 and self.level_embed is not None: - nn.init.normal_(self.level_embed) - - def get_valid_ratio(self, mask): - _, H, W = mask.shape - valid_H = torch.sum(~mask[:, :, 0], 1) - valid_W = torch.sum(~mask[:, 0, :], 1) - valid_ratio_h = valid_H.float() / H - valid_ratio_w = valid_W.float() / W - valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1) - return valid_ratio - - def init_ref_points(self, use_num_queries): - self.refpoint_embed = nn.Embedding(use_num_queries, 4) - - def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None, text_dict=None): - """ - Input: - - srcs: List of multi features [bs, ci, hi, wi] - - masks: List of multi masks [bs, hi, wi] - - refpoint_embed: [bs, num_dn, 4]. None in infer - - pos_embeds: List of multi pos embeds [bs, ci, hi, wi] - - tgt: [bs, num_dn, d_model]. None in infer - - """ - # prepare input for encoder - src_flatten = [] - mask_flatten = [] - lvl_pos_embed_flatten = [] - spatial_shapes = [] - for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)): - bs, c, h, w = src.shape - spatial_shape = (h, w) - spatial_shapes.append(spatial_shape) - - src = src.flatten(2).transpose(1, 2) # bs, hw, c - mask = mask.flatten(1) # bs, hw - pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c - if self.num_feature_levels > 1 and self.level_embed is not None: - lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) - else: - lvl_pos_embed = pos_embed - lvl_pos_embed_flatten.append(lvl_pos_embed) - src_flatten.append(src) - mask_flatten.append(mask) - src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c - mask_flatten = torch.cat(mask_flatten, 1) # bs, \sum{hxw} - lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c - spatial_shapes = torch.as_tensor( - spatial_shapes, dtype=torch.long, device=src_flatten.device - ) - level_start_index = torch.cat( - (spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]) - ) - valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1) - - # two stage - enc_topk_proposals = enc_refpoint_embed = None - - ######################################################### - # Begin Encoder - ######################################################### - memory, memory_text = self.encoder( - src_flatten, - pos=lvl_pos_embed_flatten, - level_start_index=level_start_index, - spatial_shapes=spatial_shapes, - valid_ratios=valid_ratios, - key_padding_mask=mask_flatten, - memory_text=text_dict["encoded_text"], - text_attention_mask=~text_dict["text_token_mask"], - # we ~ the mask . False means use the token; True means pad the token - position_ids=text_dict["position_ids"], - text_self_attention_masks=text_dict["text_self_attention_masks"], - ) - ######################################################### - # End Encoder - # - memory: bs, \sum{hw}, c - # - mask_flatten: bs, \sum{hw} - # - lvl_pos_embed_flatten: bs, \sum{hw}, c - # - enc_intermediate_output: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c) - # - enc_intermediate_refpoints: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c) - ######################################################### - text_dict["encoded_text"] = memory_text - # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': - # if memory.isnan().any() | memory.isinf().any(): - # import ipdb; ipdb.set_trace() - - if self.two_stage_type == "standard": - output_memory, output_proposals = gen_encoder_output_proposals( - memory, mask_flatten, spatial_shapes - ) - output_memory = self.enc_output_norm(self.enc_output(output_memory)) - - if text_dict is not None: - enc_outputs_class_unselected = self.enc_out_class_embed(output_memory, text_dict) - else: - enc_outputs_class_unselected = self.enc_out_class_embed(output_memory) - - topk_logits = enc_outputs_class_unselected.max(-1)[0] - enc_outputs_coord_unselected = ( - self.enc_out_bbox_embed(output_memory) + output_proposals - ) # (bs, \sum{hw}, 4) unsigmoid - topk = self.num_queries - - topk_proposals = torch.topk(topk_logits, topk, dim=1)[1] # bs, nq - - # gather boxes - refpoint_embed_undetach = torch.gather( - enc_outputs_coord_unselected, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4) - ) # unsigmoid - refpoint_embed_ = refpoint_embed_undetach.detach() - init_box_proposal = torch.gather( - output_proposals, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4) - ).sigmoid() # sigmoid - - # gather tgt - tgt_undetach = torch.gather( - output_memory, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, self.d_model) - ) - if self.embed_init_tgt: - tgt_ = ( - self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) - ) # nq, bs, d_model - else: - tgt_ = tgt_undetach.detach() - - if refpoint_embed is not None: - refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1) - tgt = torch.cat([tgt, tgt_], dim=1) - else: - refpoint_embed, tgt = refpoint_embed_, tgt_ - - elif self.two_stage_type == "no": - tgt_ = ( - self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) - ) # nq, bs, d_model - refpoint_embed_ = ( - self.refpoint_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) - ) # nq, bs, 4 - - if refpoint_embed is not None: - refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1) - tgt = torch.cat([tgt, tgt_], dim=1) - else: - refpoint_embed, tgt = refpoint_embed_, tgt_ - - if self.num_patterns > 0: - tgt_embed = tgt.repeat(1, self.num_patterns, 1) - refpoint_embed = refpoint_embed.repeat(1, self.num_patterns, 1) - tgt_pat = self.patterns.weight[None, :, :].repeat_interleave( - self.num_queries, 1 - ) # 1, n_q*n_pat, d_model - tgt = tgt_embed + tgt_pat - - init_box_proposal = refpoint_embed_.sigmoid() - - else: - raise NotImplementedError("unknown two_stage_type {}".format(self.two_stage_type)) - ######################################################### - # End preparing tgt - # - tgt: bs, NQ, d_model - # - refpoint_embed(unsigmoid): bs, NQ, d_model - ######################################################### - - ######################################################### - # Begin Decoder - ######################################################### - hs, references = self.decoder( - tgt=tgt.transpose(0, 1), - memory=memory.transpose(0, 1), - memory_key_padding_mask=mask_flatten, - pos=lvl_pos_embed_flatten.transpose(0, 1), - refpoints_unsigmoid=refpoint_embed.transpose(0, 1), - level_start_index=level_start_index, - spatial_shapes=spatial_shapes, - valid_ratios=valid_ratios, - tgt_mask=attn_mask, - memory_text=text_dict["encoded_text"], - text_attention_mask=~text_dict["text_token_mask"], - # we ~ the mask . False means use the token; True means pad the token - ) - ######################################################### - # End Decoder - # hs: n_dec, bs, nq, d_model - # references: n_dec+1, bs, nq, query_dim - ######################################################### - - ######################################################### - # Begin postprocess - ######################################################### - if self.two_stage_type == "standard": - hs_enc = tgt_undetach.unsqueeze(0) - ref_enc = refpoint_embed_undetach.sigmoid().unsqueeze(0) - else: - hs_enc = ref_enc = None - ######################################################### - # End postprocess - # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or (n_enc, bs, nq, d_model) or None - # ref_enc: (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or (n_enc, bs, nq, d_model) or None - ######################################################### - - return hs, references, hs_enc, ref_enc, init_box_proposal - # hs: (n_dec, bs, nq, d_model) - # references: sigmoid coordinates. (n_dec+1, bs, bq, 4) - # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or None - # ref_enc: sigmoid coordinates. \ - # (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or None - - -class TransformerEncoder(nn.Module): - def __init__( - self, - encoder_layer, - num_layers, - d_model=256, - num_queries=300, - enc_layer_share=False, - text_enhance_layer=None, - feature_fusion_layer=None, - use_checkpoint=False, - use_transformer_ckpt=False, - ): - """_summary_ - - Args: - encoder_layer (_type_): _description_ - num_layers (_type_): _description_ - norm (_type_, optional): _description_. Defaults to None. - d_model (int, optional): _description_. Defaults to 256. - num_queries (int, optional): _description_. Defaults to 300. - enc_layer_share (bool, optional): _description_. Defaults to False. - - """ - super().__init__() - # prepare layers - self.layers = [] - self.text_layers = [] - self.fusion_layers = [] - if num_layers > 0: - self.layers = _get_clones(encoder_layer, num_layers, layer_share=enc_layer_share) - - if text_enhance_layer is not None: - self.text_layers = _get_clones( - text_enhance_layer, num_layers, layer_share=enc_layer_share - ) - if feature_fusion_layer is not None: - self.fusion_layers = _get_clones( - feature_fusion_layer, num_layers, layer_share=enc_layer_share - ) - else: - self.layers = [] - del encoder_layer - - if text_enhance_layer is not None: - self.text_layers = [] - del text_enhance_layer - if feature_fusion_layer is not None: - self.fusion_layers = [] - del feature_fusion_layer - - self.query_scale = None - self.num_queries = num_queries - self.num_layers = num_layers - self.d_model = d_model - - self.use_checkpoint = use_checkpoint - self.use_transformer_ckpt = use_transformer_ckpt - - @staticmethod - def get_reference_points(spatial_shapes, valid_ratios, device): - reference_points_list = [] - for lvl, (H_, W_) in enumerate(spatial_shapes): - - ref_y, ref_x = torch.meshgrid( - torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device), - torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device), - ) - ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_) - ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_) - ref = torch.stack((ref_x, ref_y), -1) - reference_points_list.append(ref) - reference_points = torch.cat(reference_points_list, 1) - reference_points = reference_points[:, :, None] * valid_ratios[:, None] - return reference_points - - def forward( - self, - # for images - src: Tensor, - pos: Tensor, - spatial_shapes: Tensor, - level_start_index: Tensor, - valid_ratios: Tensor, - key_padding_mask: Tensor, - # for texts - memory_text: Tensor = None, - text_attention_mask: Tensor = None, - pos_text: Tensor = None, - text_self_attention_masks: Tensor = None, - position_ids: Tensor = None, - ): - """ - Input: - - src: [bs, sum(hi*wi), 256] - - pos: pos embed for src. [bs, sum(hi*wi), 256] - - spatial_shapes: h,w of each level [num_level, 2] - - level_start_index: [num_level] start point of level in sum(hi*wi). - - valid_ratios: [bs, num_level, 2] - - key_padding_mask: [bs, sum(hi*wi)] - - - memory_text: bs, n_text, 256 - - text_attention_mask: bs, n_text - False for no padding; True for padding - - pos_text: bs, n_text, 256 - - - position_ids: bs, n_text - Intermedia: - - reference_points: [bs, sum(hi*wi), num_level, 2] - Outpus: - - output: [bs, sum(hi*wi), 256] - """ - - output = src - - # preparation and reshape - if self.num_layers > 0: - reference_points = self.get_reference_points( - spatial_shapes, valid_ratios, device=src.device - ) - - if self.text_layers: - # generate pos_text - bs, n_text, text_dim = memory_text.shape - if pos_text is None and position_ids is None: - pos_text = ( - torch.arange(n_text, device=memory_text.device) - .float() - .unsqueeze(0) - .unsqueeze(-1) - .repeat(bs, 1, 1) - ) - pos_text = get_sine_pos_embed(pos_text, num_pos_feats=256, exchange_xy=False) - if position_ids is not None: - pos_text = get_sine_pos_embed( - position_ids[..., None], num_pos_feats=256, exchange_xy=False - ) - - # main process - for layer_id, layer in enumerate(self.layers): - # if output.isnan().any() or memory_text.isnan().any(): - # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO': - # import ipdb; ipdb.set_trace() - if self.fusion_layers: - if self.use_checkpoint: - output, memory_text = checkpoint.checkpoint( - self.fusion_layers[layer_id], - output, - memory_text, - key_padding_mask, - text_attention_mask, - ) - else: - output, memory_text = self.fusion_layers[layer_id]( - v=output, - l=memory_text, - attention_mask_v=key_padding_mask, - attention_mask_l=text_attention_mask, - ) - - if self.text_layers: - memory_text = self.text_layers[layer_id]( - src=memory_text.transpose(0, 1), - src_mask=~text_self_attention_masks, # note we use ~ for mask here - src_key_padding_mask=text_attention_mask, - pos=(pos_text.transpose(0, 1) if pos_text is not None else None), - ).transpose(0, 1) - - # main process - if self.use_transformer_ckpt: - output = checkpoint.checkpoint( - layer, - output, - pos, - reference_points, - spatial_shapes, - level_start_index, - key_padding_mask, - ) - else: - output = layer( - src=output, - pos=pos, - reference_points=reference_points, - spatial_shapes=spatial_shapes, - level_start_index=level_start_index, - key_padding_mask=key_padding_mask, - ) - - return output, memory_text - - -class TransformerDecoder(nn.Module): - def __init__( - self, - decoder_layer, - num_layers, - norm=None, - return_intermediate=False, - d_model=256, - query_dim=4, - num_feature_levels=1, - ): - super().__init__() - if num_layers > 0: - self.layers = _get_clones(decoder_layer, num_layers) - else: - self.layers = [] - self.num_layers = num_layers - self.norm = norm - self.return_intermediate = return_intermediate - assert return_intermediate, "support return_intermediate only" - self.query_dim = query_dim - assert query_dim in [2, 4], "query_dim should be 2/4 but {}".format(query_dim) - self.num_feature_levels = num_feature_levels - - self.ref_point_head = MLP(query_dim // 2 * d_model, d_model, d_model, 2) - self.query_pos_sine_scale = None - - self.query_scale = None - self.bbox_embed = None - self.class_embed = None - - self.d_model = d_model - - self.ref_anchor_head = None - - def forward( - self, - tgt, - memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - refpoints_unsigmoid: Optional[Tensor] = None, # num_queries, bs, 2 - # for memory - level_start_index: Optional[Tensor] = None, # num_levels - spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2 - valid_ratios: Optional[Tensor] = None, - # for text - memory_text: Optional[Tensor] = None, - text_attention_mask: Optional[Tensor] = None, - ): - """ - Input: - - tgt: nq, bs, d_model - - memory: hw, bs, d_model - - pos: hw, bs, d_model - - refpoints_unsigmoid: nq, bs, 2/4 - - valid_ratios/spatial_shapes: bs, nlevel, 2 - """ - output = tgt - - intermediate = [] - reference_points = refpoints_unsigmoid.sigmoid() - ref_points = [reference_points] - - for layer_id, layer in enumerate(self.layers): - - if reference_points.shape[-1] == 4: - reference_points_input = ( - reference_points[:, :, None] - * torch.cat([valid_ratios, valid_ratios], -1)[None, :] - ) # nq, bs, nlevel, 4 - else: - assert reference_points.shape[-1] == 2 - reference_points_input = reference_points[:, :, None] * valid_ratios[None, :] - query_sine_embed = gen_sineembed_for_position( - reference_points_input[:, :, 0, :] - ) # nq, bs, 256*2 - - # conditional query - raw_query_pos = self.ref_point_head(query_sine_embed) # nq, bs, 256 - pos_scale = self.query_scale(output) if self.query_scale is not None else 1 - query_pos = pos_scale * raw_query_pos - # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': - # if query_pos.isnan().any() | query_pos.isinf().any(): - # import ipdb; ipdb.set_trace() - - # main process - output = layer( - tgt=output, - tgt_query_pos=query_pos, - tgt_query_sine_embed=query_sine_embed, - tgt_key_padding_mask=tgt_key_padding_mask, - tgt_reference_points=reference_points_input, - memory_text=memory_text, - text_attention_mask=text_attention_mask, - memory=memory, - memory_key_padding_mask=memory_key_padding_mask, - memory_level_start_index=level_start_index, - memory_spatial_shapes=spatial_shapes, - memory_pos=pos, - self_attn_mask=tgt_mask, - cross_attn_mask=memory_mask, - ) - if output.isnan().any() | output.isinf().any(): - print(f"output layer_id {layer_id} is nan") - try: - num_nan = output.isnan().sum().item() - num_inf = output.isinf().sum().item() - print(f"num_nan {num_nan}, num_inf {num_inf}") - except Exception as e: - print(e) - # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': - # import ipdb; ipdb.set_trace() - - # iter update - if self.bbox_embed is not None: - # box_holder = self.bbox_embed(output) - # box_holder[..., :self.query_dim] += inverse_sigmoid(reference_points) - # new_reference_points = box_holder[..., :self.query_dim].sigmoid() - - reference_before_sigmoid = inverse_sigmoid(reference_points) - delta_unsig = self.bbox_embed[layer_id](output) - outputs_unsig = delta_unsig + reference_before_sigmoid - new_reference_points = outputs_unsig.sigmoid() - - reference_points = new_reference_points.detach() - # if layer_id != self.num_layers - 1: - ref_points.append(new_reference_points) - - intermediate.append(self.norm(output)) - - return [ - [itm_out.transpose(0, 1) for itm_out in intermediate], - [itm_refpoint.transpose(0, 1) for itm_refpoint in ref_points], - ] - - -class DeformableTransformerEncoderLayer(nn.Module): - def __init__( - self, - d_model=256, - d_ffn=1024, - dropout=0.1, - activation="relu", - n_levels=4, - n_heads=8, - n_points=4, - ): - super().__init__() - - # self attention - self.self_attn = MSDeformAttn( - embed_dim=d_model, - num_levels=n_levels, - num_heads=n_heads, - num_points=n_points, - batch_first=True, - ) - self.dropout1 = nn.Dropout(dropout) - self.norm1 = nn.LayerNorm(d_model) - - # ffn - self.linear1 = nn.Linear(d_model, d_ffn) - self.activation = _get_activation_fn(activation, d_model=d_ffn) - self.dropout2 = nn.Dropout(dropout) - self.linear2 = nn.Linear(d_ffn, d_model) - self.dropout3 = nn.Dropout(dropout) - self.norm2 = nn.LayerNorm(d_model) - - @staticmethod - def with_pos_embed(tensor, pos): - return tensor if pos is None else tensor + pos - - def forward_ffn(self, src): - src2 = self.linear2(self.dropout2(self.activation(self.linear1(src)))) - src = src + self.dropout3(src2) - src = self.norm2(src) - return src - - def forward( - self, src, pos, reference_points, spatial_shapes, level_start_index, key_padding_mask=None - ): - # self attention - # import ipdb; ipdb.set_trace() - src2 = self.self_attn( - query=self.with_pos_embed(src, pos), - reference_points=reference_points, - value=src, - spatial_shapes=spatial_shapes, - level_start_index=level_start_index, - key_padding_mask=key_padding_mask, - ) - src = src + self.dropout1(src2) - src = self.norm1(src) - - # ffn - src = self.forward_ffn(src) - - return src - - -class DeformableTransformerDecoderLayer(nn.Module): - def __init__( - self, - d_model=256, - d_ffn=1024, - dropout=0.1, - activation="relu", - n_levels=4, - n_heads=8, - n_points=4, - use_text_feat_guide=False, - use_text_cross_attention=False, - ): - super().__init__() - - # cross attention - self.cross_attn = MSDeformAttn( - embed_dim=d_model, - num_levels=n_levels, - num_heads=n_heads, - num_points=n_points, - batch_first=True, - ) - self.dropout1 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() - self.norm1 = nn.LayerNorm(d_model) - - # cross attention text - if use_text_cross_attention: - self.ca_text = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) - self.catext_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() - self.catext_norm = nn.LayerNorm(d_model) - - # self attention - self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) - self.dropout2 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() - self.norm2 = nn.LayerNorm(d_model) - - # ffn - self.linear1 = nn.Linear(d_model, d_ffn) - self.activation = _get_activation_fn(activation, d_model=d_ffn, batch_dim=1) - self.dropout3 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() - self.linear2 = nn.Linear(d_ffn, d_model) - self.dropout4 = nn.Dropout(dropout) if dropout > 0 else nn.Identity() - self.norm3 = nn.LayerNorm(d_model) - - self.key_aware_proj = None - self.use_text_feat_guide = use_text_feat_guide - assert not use_text_feat_guide - self.use_text_cross_attention = use_text_cross_attention - - def rm_self_attn_modules(self): - self.self_attn = None - self.dropout2 = None - self.norm2 = None - - @staticmethod - def with_pos_embed(tensor, pos): - return tensor if pos is None else tensor + pos - - def forward_ffn(self, tgt): - with torch.cuda.amp.autocast(enabled=False): - tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt)))) - tgt = tgt + self.dropout4(tgt2) - tgt = self.norm3(tgt) - return tgt - - def forward( - self, - # for tgt - tgt: Optional[Tensor], # nq, bs, d_model - tgt_query_pos: Optional[Tensor] = None, # pos for query. MLP(Sine(pos)) - tgt_query_sine_embed: Optional[Tensor] = None, # pos for query. Sine(pos) - tgt_key_padding_mask: Optional[Tensor] = None, - tgt_reference_points: Optional[Tensor] = None, # nq, bs, 4 - memory_text: Optional[Tensor] = None, # bs, num_token, d_model - text_attention_mask: Optional[Tensor] = None, # bs, num_token - # for memory - memory: Optional[Tensor] = None, # hw, bs, d_model - memory_key_padding_mask: Optional[Tensor] = None, - memory_level_start_index: Optional[Tensor] = None, # num_levels - memory_spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2 - memory_pos: Optional[Tensor] = None, # pos for memory - # sa - self_attn_mask: Optional[Tensor] = None, # mask used for self-attention - cross_attn_mask: Optional[Tensor] = None, # mask used for cross-attention - ): - """ - Input: - - tgt/tgt_query_pos: nq, bs, d_model - - - """ - assert cross_attn_mask is None - - # self attention - if self.self_attn is not None: - # import ipdb; ipdb.set_trace() - q = k = self.with_pos_embed(tgt, tgt_query_pos) - tgt2 = self.self_attn(q, k, tgt, attn_mask=self_attn_mask)[0] - tgt = tgt + self.dropout2(tgt2) - tgt = self.norm2(tgt) - - if self.use_text_cross_attention: - tgt2 = self.ca_text( - self.with_pos_embed(tgt, tgt_query_pos), - memory_text.transpose(0, 1), - memory_text.transpose(0, 1), - key_padding_mask=text_attention_mask, - )[0] - tgt = tgt + self.catext_dropout(tgt2) - tgt = self.catext_norm(tgt) - - tgt2 = self.cross_attn( - query=self.with_pos_embed(tgt, tgt_query_pos).transpose(0, 1), - reference_points=tgt_reference_points.transpose(0, 1).contiguous(), - value=memory.transpose(0, 1), - spatial_shapes=memory_spatial_shapes, - level_start_index=memory_level_start_index, - key_padding_mask=memory_key_padding_mask, - ).transpose(0, 1) - tgt = tgt + self.dropout1(tgt2) - tgt = self.norm1(tgt) - - # ffn - tgt = self.forward_ffn(tgt) - - return tgt - - -def build_transformer(args): - return Transformer( - d_model=args.hidden_dim, - dropout=args.dropout, - nhead=args.nheads, - num_queries=args.num_queries, - dim_feedforward=args.dim_feedforward, - num_encoder_layers=args.enc_layers, - num_decoder_layers=args.dec_layers, - normalize_before=args.pre_norm, - return_intermediate_dec=True, - query_dim=args.query_dim, - activation=args.transformer_activation, - num_patterns=args.num_patterns, - num_feature_levels=args.num_feature_levels, - enc_n_points=args.enc_n_points, - dec_n_points=args.dec_n_points, - learnable_tgt_init=True, - # two stage - two_stage_type=args.two_stage_type, # ['no', 'standard', 'early'] - embed_init_tgt=args.embed_init_tgt, - use_text_enhancer=args.use_text_enhancer, - use_fusion_layer=args.use_fusion_layer, - use_checkpoint=args.use_checkpoint, - use_transformer_ckpt=args.use_transformer_ckpt, - use_text_cross_attention=args.use_text_cross_attention, - text_dropout=args.text_dropout, - fusion_dropout=args.fusion_dropout, - fusion_droppath=args.fusion_droppath, - ) diff --git a/spaces/vinthony/SadTalker/src/utils/videoio.py b/spaces/vinthony/SadTalker/src/utils/videoio.py deleted file mode 100644 index d16ee667713a16e3f9644fcc3cb3e023bc2c9102..0000000000000000000000000000000000000000 --- a/spaces/vinthony/SadTalker/src/utils/videoio.py +++ /dev/null @@ -1,41 +0,0 @@ -import shutil -import uuid - -import os - -import cv2 - -def load_video_to_cv2(input_path): - video_stream = cv2.VideoCapture(input_path) - fps = video_stream.get(cv2.CAP_PROP_FPS) - full_frames = [] - while 1: - still_reading, frame = video_stream.read() - if not still_reading: - video_stream.release() - break - full_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) - return full_frames - -def save_video_with_watermark(video, audio, save_path, watermark=False): - temp_file = str(uuid.uuid4())+'.mp4' - cmd = r'ffmpeg -y -hide_banner -loglevel error -i "%s" -i "%s" -vcodec mpeg4 "%s"' % (video, audio, temp_file) - os.system(cmd) - - if watermark is False: - shutil.move(temp_file, save_path) - else: - # watermark - try: - ##### check if stable-diffusion-webui - import webui - from modules import paths - watarmark_path = paths.script_path+"/extensions/SadTalker/docs/sadtalker_logo.png" - except: - # get the root path of sadtalker. - dir_path = os.path.dirname(os.path.realpath(__file__)) - watarmark_path = dir_path+"/../../docs/sadtalker_logo.png" - - cmd = r'ffmpeg -y -hide_banner -loglevel error -i "%s" -i "%s" -filter_complex "[1]scale=100:-1[wm];[0][wm]overlay=(main_w-overlay_w)-10:10" "%s"' % (temp_file, watarmark_path, save_path) - os.system(cmd) - os.remove(temp_file) \ No newline at end of file diff --git a/spaces/vumichien/Generate_human_motion/README.md b/spaces/vumichien/Generate_human_motion/README.md deleted file mode 100644 index 7cee3a281fb2e3cd4fa871fa4dbe35eb546c3f5a..0000000000000000000000000000000000000000 --- a/spaces/vumichien/Generate_human_motion/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Generate Human Motion -emoji: 🏃 -colorFrom: green -colorTo: yellow -sdk: gradio -sdk_version: 3.50.2 -app_file: app.py -pinned: false -license: apache-2.0 -tags: -- making-demos ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/vumichien/canvas_controlnet/annotator/uniformer/mmcv/cnn/utils/weight_init.py b/spaces/vumichien/canvas_controlnet/annotator/uniformer/mmcv/cnn/utils/weight_init.py deleted file mode 100644 index 287a1d0bffe26e023029d48634d9b761deda7ba4..0000000000000000000000000000000000000000 --- a/spaces/vumichien/canvas_controlnet/annotator/uniformer/mmcv/cnn/utils/weight_init.py +++ /dev/null @@ -1,684 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import copy -import math -import warnings - -import numpy as np -import torch -import torch.nn as nn -from torch import Tensor - -from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log - -INITIALIZERS = Registry('initializer') - - -def update_init_info(module, init_info): - """Update the `_params_init_info` in the module if the value of parameters - are changed. - - Args: - module (obj:`nn.Module`): The module of PyTorch with a user-defined - attribute `_params_init_info` which records the initialization - information. - init_info (str): The string that describes the initialization. - """ - assert hasattr( - module, - '_params_init_info'), f'Can not find `_params_init_info` in {module}' - for name, param in module.named_parameters(): - - assert param in module._params_init_info, ( - f'Find a new :obj:`Parameter` ' - f'named `{name}` during executing the ' - f'`init_weights` of ' - f'`{module.__class__.__name__}`. ' - f'Please do not add or ' - f'replace parameters during executing ' - f'the `init_weights`. ') - - # The parameter has been changed during executing the - # `init_weights` of module - mean_value = param.data.mean() - if module._params_init_info[param]['tmp_mean_value'] != mean_value: - module._params_init_info[param]['init_info'] = init_info - module._params_init_info[param]['tmp_mean_value'] = mean_value - - -def constant_init(module, val, bias=0): - if hasattr(module, 'weight') and module.weight is not None: - nn.init.constant_(module.weight, val) - if hasattr(module, 'bias') and module.bias is not None: - nn.init.constant_(module.bias, bias) - - -def xavier_init(module, gain=1, bias=0, distribution='normal'): - assert distribution in ['uniform', 'normal'] - if hasattr(module, 'weight') and module.weight is not None: - if distribution == 'uniform': - nn.init.xavier_uniform_(module.weight, gain=gain) - else: - nn.init.xavier_normal_(module.weight, gain=gain) - if hasattr(module, 'bias') and module.bias is not None: - nn.init.constant_(module.bias, bias) - - -def normal_init(module, mean=0, std=1, bias=0): - if hasattr(module, 'weight') and module.weight is not None: - nn.init.normal_(module.weight, mean, std) - if hasattr(module, 'bias') and module.bias is not None: - nn.init.constant_(module.bias, bias) - - -def trunc_normal_init(module: nn.Module, - mean: float = 0, - std: float = 1, - a: float = -2, - b: float = 2, - bias: float = 0) -> None: - if hasattr(module, 'weight') and module.weight is not None: - trunc_normal_(module.weight, mean, std, a, b) # type: ignore - if hasattr(module, 'bias') and module.bias is not None: - nn.init.constant_(module.bias, bias) # type: ignore - - -def uniform_init(module, a=0, b=1, bias=0): - if hasattr(module, 'weight') and module.weight is not None: - nn.init.uniform_(module.weight, a, b) - if hasattr(module, 'bias') and module.bias is not None: - nn.init.constant_(module.bias, bias) - - -def kaiming_init(module, - a=0, - mode='fan_out', - nonlinearity='relu', - bias=0, - distribution='normal'): - assert distribution in ['uniform', 'normal'] - if hasattr(module, 'weight') and module.weight is not None: - if distribution == 'uniform': - nn.init.kaiming_uniform_( - module.weight, a=a, mode=mode, nonlinearity=nonlinearity) - else: - nn.init.kaiming_normal_( - module.weight, a=a, mode=mode, nonlinearity=nonlinearity) - if hasattr(module, 'bias') and module.bias is not None: - nn.init.constant_(module.bias, bias) - - -def caffe2_xavier_init(module, bias=0): - # `XavierFill` in Caffe2 corresponds to `kaiming_uniform_` in PyTorch - # Acknowledgment to FAIR's internal code - kaiming_init( - module, - a=1, - mode='fan_in', - nonlinearity='leaky_relu', - bias=bias, - distribution='uniform') - - -def bias_init_with_prob(prior_prob): - """initialize conv/fc bias value according to a given probability value.""" - bias_init = float(-np.log((1 - prior_prob) / prior_prob)) - return bias_init - - -def _get_bases_name(m): - return [b.__name__ for b in m.__class__.__bases__] - - -class BaseInit(object): - - def __init__(self, *, bias=0, bias_prob=None, layer=None): - self.wholemodule = False - if not isinstance(bias, (int, float)): - raise TypeError(f'bias must be a number, but got a {type(bias)}') - - if bias_prob is not None: - if not isinstance(bias_prob, float): - raise TypeError(f'bias_prob type must be float, \ - but got {type(bias_prob)}') - - if layer is not None: - if not isinstance(layer, (str, list)): - raise TypeError(f'layer must be a str or a list of str, \ - but got a {type(layer)}') - else: - layer = [] - - if bias_prob is not None: - self.bias = bias_init_with_prob(bias_prob) - else: - self.bias = bias - self.layer = [layer] if isinstance(layer, str) else layer - - def _get_init_info(self): - info = f'{self.__class__.__name__}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='Constant') -class ConstantInit(BaseInit): - """Initialize module parameters with constant values. - - Args: - val (int | float): the value to fill the weights in the module with - bias (int | float): the value to fill the bias. Defaults to 0. - bias_prob (float, optional): the probability for bias initialization. - Defaults to None. - layer (str | list[str], optional): the layer will be initialized. - Defaults to None. - """ - - def __init__(self, val, **kwargs): - super().__init__(**kwargs) - self.val = val - - def __call__(self, module): - - def init(m): - if self.wholemodule: - constant_init(m, self.val, self.bias) - else: - layername = m.__class__.__name__ - basesname = _get_bases_name(m) - if len(set(self.layer) & set([layername] + basesname)): - constant_init(m, self.val, self.bias) - - module.apply(init) - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: val={self.val}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='Xavier') -class XavierInit(BaseInit): - r"""Initialize module parameters with values according to the method - described in `Understanding the difficulty of training deep feedforward - neural networks - Glorot, X. & Bengio, Y. (2010). - `_ - - Args: - gain (int | float): an optional scaling factor. Defaults to 1. - bias (int | float): the value to fill the bias. Defaults to 0. - bias_prob (float, optional): the probability for bias initialization. - Defaults to None. - distribution (str): distribution either be ``'normal'`` - or ``'uniform'``. Defaults to ``'normal'``. - layer (str | list[str], optional): the layer will be initialized. - Defaults to None. - """ - - def __init__(self, gain=1, distribution='normal', **kwargs): - super().__init__(**kwargs) - self.gain = gain - self.distribution = distribution - - def __call__(self, module): - - def init(m): - if self.wholemodule: - xavier_init(m, self.gain, self.bias, self.distribution) - else: - layername = m.__class__.__name__ - basesname = _get_bases_name(m) - if len(set(self.layer) & set([layername] + basesname)): - xavier_init(m, self.gain, self.bias, self.distribution) - - module.apply(init) - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: gain={self.gain}, ' \ - f'distribution={self.distribution}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='Normal') -class NormalInit(BaseInit): - r"""Initialize module parameters with the values drawn from the normal - distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`. - - Args: - mean (int | float):the mean of the normal distribution. Defaults to 0. - std (int | float): the standard deviation of the normal distribution. - Defaults to 1. - bias (int | float): the value to fill the bias. Defaults to 0. - bias_prob (float, optional): the probability for bias initialization. - Defaults to None. - layer (str | list[str], optional): the layer will be initialized. - Defaults to None. - - """ - - def __init__(self, mean=0, std=1, **kwargs): - super().__init__(**kwargs) - self.mean = mean - self.std = std - - def __call__(self, module): - - def init(m): - if self.wholemodule: - normal_init(m, self.mean, self.std, self.bias) - else: - layername = m.__class__.__name__ - basesname = _get_bases_name(m) - if len(set(self.layer) & set([layername] + basesname)): - normal_init(m, self.mean, self.std, self.bias) - - module.apply(init) - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: mean={self.mean},' \ - f' std={self.std}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='TruncNormal') -class TruncNormalInit(BaseInit): - r"""Initialize module parameters with the values drawn from the normal - distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values - outside :math:`[a, b]`. - - Args: - mean (float): the mean of the normal distribution. Defaults to 0. - std (float): the standard deviation of the normal distribution. - Defaults to 1. - a (float): The minimum cutoff value. - b ( float): The maximum cutoff value. - bias (float): the value to fill the bias. Defaults to 0. - bias_prob (float, optional): the probability for bias initialization. - Defaults to None. - layer (str | list[str], optional): the layer will be initialized. - Defaults to None. - - """ - - def __init__(self, - mean: float = 0, - std: float = 1, - a: float = -2, - b: float = 2, - **kwargs) -> None: - super().__init__(**kwargs) - self.mean = mean - self.std = std - self.a = a - self.b = b - - def __call__(self, module: nn.Module) -> None: - - def init(m): - if self.wholemodule: - trunc_normal_init(m, self.mean, self.std, self.a, self.b, - self.bias) - else: - layername = m.__class__.__name__ - basesname = _get_bases_name(m) - if len(set(self.layer) & set([layername] + basesname)): - trunc_normal_init(m, self.mean, self.std, self.a, self.b, - self.bias) - - module.apply(init) - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: a={self.a}, b={self.b},' \ - f' mean={self.mean}, std={self.std}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='Uniform') -class UniformInit(BaseInit): - r"""Initialize module parameters with values drawn from the uniform - distribution :math:`\mathcal{U}(a, b)`. - - Args: - a (int | float): the lower bound of the uniform distribution. - Defaults to 0. - b (int | float): the upper bound of the uniform distribution. - Defaults to 1. - bias (int | float): the value to fill the bias. Defaults to 0. - bias_prob (float, optional): the probability for bias initialization. - Defaults to None. - layer (str | list[str], optional): the layer will be initialized. - Defaults to None. - """ - - def __init__(self, a=0, b=1, **kwargs): - super().__init__(**kwargs) - self.a = a - self.b = b - - def __call__(self, module): - - def init(m): - if self.wholemodule: - uniform_init(m, self.a, self.b, self.bias) - else: - layername = m.__class__.__name__ - basesname = _get_bases_name(m) - if len(set(self.layer) & set([layername] + basesname)): - uniform_init(m, self.a, self.b, self.bias) - - module.apply(init) - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: a={self.a},' \ - f' b={self.b}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='Kaiming') -class KaimingInit(BaseInit): - r"""Initialize module parameters with the values according to the method - described in `Delving deep into rectifiers: Surpassing human-level - performance on ImageNet classification - He, K. et al. (2015). - `_ - - Args: - a (int | float): the negative slope of the rectifier used after this - layer (only used with ``'leaky_relu'``). Defaults to 0. - mode (str): either ``'fan_in'`` or ``'fan_out'``. Choosing - ``'fan_in'`` preserves the magnitude of the variance of the weights - in the forward pass. Choosing ``'fan_out'`` preserves the - magnitudes in the backwards pass. Defaults to ``'fan_out'``. - nonlinearity (str): the non-linear function (`nn.functional` name), - recommended to use only with ``'relu'`` or ``'leaky_relu'`` . - Defaults to 'relu'. - bias (int | float): the value to fill the bias. Defaults to 0. - bias_prob (float, optional): the probability for bias initialization. - Defaults to None. - distribution (str): distribution either be ``'normal'`` or - ``'uniform'``. Defaults to ``'normal'``. - layer (str | list[str], optional): the layer will be initialized. - Defaults to None. - """ - - def __init__(self, - a=0, - mode='fan_out', - nonlinearity='relu', - distribution='normal', - **kwargs): - super().__init__(**kwargs) - self.a = a - self.mode = mode - self.nonlinearity = nonlinearity - self.distribution = distribution - - def __call__(self, module): - - def init(m): - if self.wholemodule: - kaiming_init(m, self.a, self.mode, self.nonlinearity, - self.bias, self.distribution) - else: - layername = m.__class__.__name__ - basesname = _get_bases_name(m) - if len(set(self.layer) & set([layername] + basesname)): - kaiming_init(m, self.a, self.mode, self.nonlinearity, - self.bias, self.distribution) - - module.apply(init) - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: a={self.a}, mode={self.mode}, ' \ - f'nonlinearity={self.nonlinearity}, ' \ - f'distribution ={self.distribution}, bias={self.bias}' - return info - - -@INITIALIZERS.register_module(name='Caffe2Xavier') -class Caffe2XavierInit(KaimingInit): - # `XavierFill` in Caffe2 corresponds to `kaiming_uniform_` in PyTorch - # Acknowledgment to FAIR's internal code - def __init__(self, **kwargs): - super().__init__( - a=1, - mode='fan_in', - nonlinearity='leaky_relu', - distribution='uniform', - **kwargs) - - def __call__(self, module): - super().__call__(module) - - -@INITIALIZERS.register_module(name='Pretrained') -class PretrainedInit(object): - """Initialize module by loading a pretrained model. - - Args: - checkpoint (str): the checkpoint file of the pretrained model should - be load. - prefix (str, optional): the prefix of a sub-module in the pretrained - model. it is for loading a part of the pretrained model to - initialize. For example, if we would like to only load the - backbone of a detector model, we can set ``prefix='backbone.'``. - Defaults to None. - map_location (str): map tensors into proper locations. - """ - - def __init__(self, checkpoint, prefix=None, map_location=None): - self.checkpoint = checkpoint - self.prefix = prefix - self.map_location = map_location - - def __call__(self, module): - from annotator.uniformer.mmcv.runner import (_load_checkpoint_with_prefix, load_checkpoint, - load_state_dict) - logger = get_logger('mmcv') - if self.prefix is None: - print_log(f'load model from: {self.checkpoint}', logger=logger) - load_checkpoint( - module, - self.checkpoint, - map_location=self.map_location, - strict=False, - logger=logger) - else: - print_log( - f'load {self.prefix} in model from: {self.checkpoint}', - logger=logger) - state_dict = _load_checkpoint_with_prefix( - self.prefix, self.checkpoint, map_location=self.map_location) - load_state_dict(module, state_dict, strict=False, logger=logger) - - if hasattr(module, '_params_init_info'): - update_init_info(module, init_info=self._get_init_info()) - - def _get_init_info(self): - info = f'{self.__class__.__name__}: load from {self.checkpoint}' - return info - - -def _initialize(module, cfg, wholemodule=False): - func = build_from_cfg(cfg, INITIALIZERS) - # wholemodule flag is for override mode, there is no layer key in override - # and initializer will give init values for the whole module with the name - # in override. - func.wholemodule = wholemodule - func(module) - - -def _initialize_override(module, override, cfg): - if not isinstance(override, (dict, list)): - raise TypeError(f'override must be a dict or a list of dict, \ - but got {type(override)}') - - override = [override] if isinstance(override, dict) else override - - for override_ in override: - - cp_override = copy.deepcopy(override_) - name = cp_override.pop('name', None) - if name is None: - raise ValueError('`override` must contain the key "name",' - f'but got {cp_override}') - # if override only has name key, it means use args in init_cfg - if not cp_override: - cp_override.update(cfg) - # if override has name key and other args except type key, it will - # raise error - elif 'type' not in cp_override.keys(): - raise ValueError( - f'`override` need "type" key, but got {cp_override}') - - if hasattr(module, name): - _initialize(getattr(module, name), cp_override, wholemodule=True) - else: - raise RuntimeError(f'module did not have attribute {name}, ' - f'but init_cfg is {cp_override}.') - - -def initialize(module, init_cfg): - """Initialize a module. - - Args: - module (``torch.nn.Module``): the module will be initialized. - init_cfg (dict | list[dict]): initialization configuration dict to - define initializer. OpenMMLab has implemented 6 initializers - including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``, - ``Kaiming``, and ``Pretrained``. - Example: - >>> module = nn.Linear(2, 3, bias=True) - >>> init_cfg = dict(type='Constant', layer='Linear', val =1 , bias =2) - >>> initialize(module, init_cfg) - - >>> module = nn.Sequential(nn.Conv1d(3, 1, 3), nn.Linear(1,2)) - >>> # define key ``'layer'`` for initializing layer with different - >>> # configuration - >>> init_cfg = [dict(type='Constant', layer='Conv1d', val=1), - dict(type='Constant', layer='Linear', val=2)] - >>> initialize(module, init_cfg) - - >>> # define key``'override'`` to initialize some specific part in - >>> # module - >>> class FooNet(nn.Module): - >>> def __init__(self): - >>> super().__init__() - >>> self.feat = nn.Conv2d(3, 16, 3) - >>> self.reg = nn.Conv2d(16, 10, 3) - >>> self.cls = nn.Conv2d(16, 5, 3) - >>> model = FooNet() - >>> init_cfg = dict(type='Constant', val=1, bias=2, layer='Conv2d', - >>> override=dict(type='Constant', name='reg', val=3, bias=4)) - >>> initialize(model, init_cfg) - - >>> model = ResNet(depth=50) - >>> # Initialize weights with the pretrained model. - >>> init_cfg = dict(type='Pretrained', - checkpoint='torchvision://resnet50') - >>> initialize(model, init_cfg) - - >>> # Initialize weights of a sub-module with the specific part of - >>> # a pretrained model by using "prefix". - >>> url = 'http://download.openmmlab.com/mmdetection/v2.0/retinanet/'\ - >>> 'retinanet_r50_fpn_1x_coco/'\ - >>> 'retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth' - >>> init_cfg = dict(type='Pretrained', - checkpoint=url, prefix='backbone.') - """ - if not isinstance(init_cfg, (dict, list)): - raise TypeError(f'init_cfg must be a dict or a list of dict, \ - but got {type(init_cfg)}') - - if isinstance(init_cfg, dict): - init_cfg = [init_cfg] - - for cfg in init_cfg: - # should deeply copy the original config because cfg may be used by - # other modules, e.g., one init_cfg shared by multiple bottleneck - # blocks, the expected cfg will be changed after pop and will change - # the initialization behavior of other modules - cp_cfg = copy.deepcopy(cfg) - override = cp_cfg.pop('override', None) - _initialize(module, cp_cfg) - - if override is not None: - cp_cfg.pop('layer', None) - _initialize_override(module, override, cp_cfg) - else: - # All attributes in module have same initialization. - pass - - -def _no_grad_trunc_normal_(tensor: Tensor, mean: float, std: float, a: float, - b: float) -> Tensor: - # Method based on - # https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf - # Modified from - # https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py - def norm_cdf(x): - # Computes standard normal cumulative distribution function - return (1. + math.erf(x / math.sqrt(2.))) / 2. - - if (mean < a - 2 * std) or (mean > b + 2 * std): - warnings.warn( - 'mean is more than 2 std from [a, b] in nn.init.trunc_normal_. ' - 'The distribution of values may be incorrect.', - stacklevel=2) - - with torch.no_grad(): - # Values are generated by using a truncated uniform distribution and - # then using the inverse CDF for the normal distribution. - # Get upper and lower cdf values - lower = norm_cdf((a - mean) / std) - upper = norm_cdf((b - mean) / std) - - # Uniformly fill tensor with values from [lower, upper], then translate - # to [2lower-1, 2upper-1]. - tensor.uniform_(2 * lower - 1, 2 * upper - 1) - - # Use inverse cdf transform for normal distribution to get truncated - # standard normal - tensor.erfinv_() - - # Transform to proper mean, std - tensor.mul_(std * math.sqrt(2.)) - tensor.add_(mean) - - # Clamp to ensure it's in the proper range - tensor.clamp_(min=a, max=b) - return tensor - - -def trunc_normal_(tensor: Tensor, - mean: float = 0., - std: float = 1., - a: float = -2., - b: float = 2.) -> Tensor: - r"""Fills the input Tensor with values drawn from a truncated - normal distribution. The values are effectively drawn from the - normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` - with values outside :math:`[a, b]` redrawn until they are within - the bounds. The method used for generating the random values works - best when :math:`a \leq \text{mean} \leq b`. - - Modified from - https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py - - Args: - tensor (``torch.Tensor``): an n-dimensional `torch.Tensor`. - mean (float): the mean of the normal distribution. - std (float): the standard deviation of the normal distribution. - a (float): the minimum cutoff value. - b (float): the maximum cutoff value. - """ - return _no_grad_trunc_normal_(tensor, mean, std, a, b) diff --git a/spaces/welloff/ChatGPT-prompt-generator/README.md b/spaces/welloff/ChatGPT-prompt-generator/README.md deleted file mode 100644 index 9765db2c80dd4c4b938060743922163b1718e003..0000000000000000000000000000000000000000 --- a/spaces/welloff/ChatGPT-prompt-generator/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: ChatGPT Prompt Generator -emoji: 👨🏻‍🎤 -colorFrom: purple -colorTo: pink -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false -license: apache-2.0 -duplicated_from: merve/ChatGPT-prompt-generator ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/windmaple/lit/README.md b/spaces/windmaple/lit/README.md deleted file mode 100644 index fdbc9357e99c91f2f72717ec354435c3890ae104..0000000000000000000000000000000000000000 --- a/spaces/windmaple/lit/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: LIT -emoji: ⚡ -colorFrom: red -colorTo: blue -sdk: gradio -sdk_version: 3.1.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/wong26/faster-whisper-webui/docs/colab.md b/spaces/wong26/faster-whisper-webui/docs/colab.md deleted file mode 100644 index 3fcdb835327238764fb643b9bbd2e27b6e14f58c..0000000000000000000000000000000000000000 --- a/spaces/wong26/faster-whisper-webui/docs/colab.md +++ /dev/null @@ -1,20 +0,0 @@ -# Running Whisper on Google Colab - -If you don't have a decent GPU or any experience in running command-line applications, you might want to try this Google Colab instead: - -* [Google Colab - Whisper WebUI GPU](https://colab.research.google.com/drive/1qeTSvi7Bt_5RMm88ipW4fkcsMOKlDDss?usp=sharing) -* [Screenshots](https://imgur.com/a/ZfY6uBO) - -The runtime (Runtime -> Change runtime type -> Hardware accelerator) should already be set top GPU. But if not, change it to GPU. - -Then, sign in to Google if you haven't already. Next, click on "Connect" at the top right. - -Under "Checking out WebUI from Git", click on the [play icon](https://imgur.com/a/81gOLyD) that appears in "[ ]" at the left. If you get a warning, click "Run anyway". - -After this step has completed, it should be get a green check mark. Then move on to the next section under "Installing dependencies", and click in "[ ]" again. This might take approximately 30 seconds. - -Once this has completed, scroll down to the "Run WebUI" section, and click on "[ ]". This will launch the WebUI in a shared link (expires in 72 hours). To open the UI, click on the link next to "Running on public URL", which will be something like https://12xxx.gradio.app/ - -The audio length in this version is not restricted, and it will run much faster as it is backed by a GPU. You can also run it using the "Large" model. Also note that it might take some time to start the model the first time, as it may need to download a 2.8 GB file on Google's servers. - -Once you're done, you can close the WebUI session by clicking the animated close button under "Run WebUI". You can also do this if you encounter any errors and need to restart the UI. You should also go to "Manage Sessions" and terminate the session, otherwise you may end up using all your free compute credits. \ No newline at end of file diff --git a/spaces/wynb1314/bingAI/README.md b/spaces/wynb1314/bingAI/README.md deleted file mode 100644 index 04411e9bfa84e82f72461ca34bc4fa1e348b376a..0000000000000000000000000000000000000000 --- a/spaces/wynb1314/bingAI/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: BingAI -emoji: 📉 -colorFrom: yellow -colorTo: indigo -sdk: docker -pinned: false -license: mit -app_port: 8080 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/xuetao/bingo3/src/components/providers.tsx b/spaces/xuetao/bingo3/src/components/providers.tsx deleted file mode 100644 index 892226412d80fe0b05211911b9e245cd22876460..0000000000000000000000000000000000000000 --- a/spaces/xuetao/bingo3/src/components/providers.tsx +++ /dev/null @@ -1,15 +0,0 @@ -'use client' - -import * as React from 'react' -import { ThemeProvider as NextThemesProvider } from 'next-themes' -import { ThemeProviderProps } from 'next-themes/dist/types' - -import { TooltipProvider } from '@/components/ui/tooltip' - -export function Providers({ children, ...props }: ThemeProviderProps) { - return ( - - {children} - - ) -} diff --git a/spaces/xuxw98/TAPA/setup.py b/spaces/xuxw98/TAPA/setup.py deleted file mode 100644 index 94f723632e289a4de853f4e87f8d11841ee7f700..0000000000000000000000000000000000000000 --- a/spaces/xuxw98/TAPA/setup.py +++ /dev/null @@ -1,26 +0,0 @@ -import os - -from setuptools import setup, find_packages - - -_PATH_ROOT = os.path.dirname(__file__) - -with open(os.path.join(_PATH_ROOT, "README.md"), encoding="utf-8") as fo: - readme = fo.read() - -setup( - name='lit-llama', - version='0.1.0', - description='Implementation of the LLaMA language model', - author='Lightning AI', - url='https://github.com/lightning-AI/lit-llama', - install_requires=[ - "torch>=2.0.0", - "lightning @ git+https://github.com/Lightning-AI/lightning@master", - "sentencepiece", - "bitsandbytes", - ], - packages=find_packages(), - long_description=readme, - long_description_content_type="text/markdown", -) diff --git a/spaces/xuyingliKepler/xuying_falcon/README.md b/spaces/xuyingliKepler/xuying_falcon/README.md deleted file mode 100644 index 2ab4aebe218676d37a6fb194259d911ab2f49b79..0000000000000000000000000000000000000000 --- a/spaces/xuyingliKepler/xuying_falcon/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: AutoTrain Advanced -emoji: 🚀 -colorFrom: blue -colorTo: green -sdk: docker -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/yaoshining/text-generation-webui/modules/shared.py b/spaces/yaoshining/text-generation-webui/modules/shared.py deleted file mode 100644 index dfa9cd3822fb9662836e576061de663be8ea1058..0000000000000000000000000000000000000000 --- a/spaces/yaoshining/text-generation-webui/modules/shared.py +++ /dev/null @@ -1,266 +0,0 @@ -import argparse -from collections import OrderedDict -from pathlib import Path - -import yaml - -from modules.logging_colors import logger - -generation_lock = None -model = None -tokenizer = None -is_seq2seq = False -model_name = "None" -lora_names = [] - -# Chat variables -history = {'internal': [], 'visible': []} -character = 'None' -stop_everything = False -processing_message = '*Is typing...*' - -# UI elements (buttons, sliders, HTML, etc) -gradio = {} - -# For keeping the values of UI elements on page reload -persistent_interface_state = {} - -input_params = [] # Generation input parameters -reload_inputs = [] # Parameters for reloading the chat interface - -# For restarting the interface -need_restart = False - -settings = { - 'dark_theme': False, - 'autoload_model': True, - 'max_new_tokens': 200, - 'max_new_tokens_min': 1, - 'max_new_tokens_max': 2000, - 'seed': -1, - 'character': 'None', - 'name1': 'You', - 'name2': 'Assistant', - 'context': 'This is a conversation with your Assistant. It is a computer program designed to help you with various tasks such as answering questions, providing recommendations, and helping with decision making. You can ask it anything you want and it will do its best to give you accurate and relevant information.', - 'greeting': '', - 'turn_template': '', - 'custom_stopping_strings': '', - 'stop_at_newline': False, - 'add_bos_token': True, - 'ban_eos_token': False, - 'skip_special_tokens': True, - 'truncation_length': 2048, - 'truncation_length_min': 0, - 'truncation_length_max': 16384, - 'mode': 'chat', - 'start_with': '', - 'chat_style': 'cai-chat', - 'instruction_template': 'None', - 'chat-instruct_command': 'Continue the chat dialogue below. Write a single reply for the character "<|character|>".\n\n<|prompt|>', - 'chat_generation_attempts': 1, - 'chat_generation_attempts_min': 1, - 'chat_generation_attempts_max': 10, - 'default_extensions': [], - 'chat_default_extensions': ['gallery'], - 'preset': 'simple-1', - 'prompt': 'QA', -} - - -def str2bool(v): - if isinstance(v, bool): - return v - if v.lower() in ('yes', 'true', 't', 'y', '1'): - return True - elif v.lower() in ('no', 'false', 'f', 'n', '0'): - return False - else: - raise argparse.ArgumentTypeError('Boolean value expected.') - - -parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=54)) - -# Basic settings -parser.add_argument('--notebook', action='store_true', help='Launch the web UI in notebook mode, where the output is written to the same text box as the input.') -parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode with a style similar to the Character.AI website.') -parser.add_argument('--character', type=str, help='The name of the character to load in chat mode by default.') -parser.add_argument('--model', type=str, help='Name of the model to load by default.') -parser.add_argument('--lora', type=str, nargs="+", help='The list of LoRAs to load. If you want to load more than one LoRA, write the names separated by spaces.') -parser.add_argument("--model-dir", type=str, default='models/', help="Path to directory with all the models") -parser.add_argument("--lora-dir", type=str, default='loras/', help="Path to directory with all the loras") -parser.add_argument('--model-menu', action='store_true', help='Show a model menu in the terminal when the web UI is first launched.') -parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time.') -parser.add_argument('--settings', type=str, help='Load the default interface settings from this yaml file. See settings-template.yaml for an example. If you create a file called settings.yaml, this file will be loaded by default without the need to use the --settings flag.') -parser.add_argument('--extensions', type=str, nargs="+", help='The list of extensions to load. If you want to load more than one extension, write the names separated by spaces.') -parser.add_argument('--verbose', action='store_true', help='Print the prompts to the terminal.') - -# Model loader -parser.add_argument('--loader', type=str, help='Choose the model loader manually, otherwise, it will get autodetected. Valid options: transformers, autogptq, gptq-for-llama, exllama, exllama_hf, llamacpp, rwkv, flexgen') - -# Accelerate/transformers -parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text. Warning: Training on CPU is extremely slow.') -parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.') -parser.add_argument('--gpu-memory', type=str, nargs="+", help='Maximum GPU memory in GiB to be allocated per GPU. Example: --gpu-memory 10 for a single GPU, --gpu-memory 10 5 for two GPUs. You can also set values in MiB like --gpu-memory 3500MiB.') -parser.add_argument('--cpu-memory', type=str, help='Maximum CPU memory in GiB to allocate for offloaded weights. Same as above.') -parser.add_argument('--disk', action='store_true', help='If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk.') -parser.add_argument('--disk-cache-dir', type=str, default="cache", help='Directory to save the disk cache to. Defaults to "cache".') -parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision (using bitsandbytes).') -parser.add_argument('--bf16', action='store_true', help='Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.') -parser.add_argument('--no-cache', action='store_true', help='Set use_cache to False while generating text. This reduces the VRAM usage a bit at a performance cost.') -parser.add_argument('--xformers', action='store_true', help="Use xformer's memory efficient attention. This should increase your tokens/s.") -parser.add_argument('--sdp-attention', action='store_true', help="Use torch 2.0's sdp attention.") -parser.add_argument('--trust-remote-code', action='store_true', help="Set trust_remote_code=True while loading a model. Necessary for ChatGLM and Falcon.") - -# Accelerate 4-bit -parser.add_argument('--load-in-4bit', action='store_true', help='Load the model with 4-bit precision (using bitsandbytes).') -parser.add_argument('--compute_dtype', type=str, default="float16", help="compute dtype for 4-bit. Valid options: bfloat16, float16, float32.") -parser.add_argument('--quant_type', type=str, default="nf4", help='quant_type for 4-bit. Valid options: nf4, fp4.') -parser.add_argument('--use_double_quant', action='store_true', help='use_double_quant for 4-bit.') - -# llama.cpp -parser.add_argument('--threads', type=int, default=0, help='Number of threads to use.') -parser.add_argument('--n_batch', type=int, default=512, help='Maximum number of prompt tokens to batch together when calling llama_eval.') -parser.add_argument('--no-mmap', action='store_true', help='Prevent mmap from being used.') -parser.add_argument('--mlock', action='store_true', help='Force the system to keep the model in RAM.') -parser.add_argument('--cache-capacity', type=str, help='Maximum cache capacity. Examples: 2000MiB, 2GiB. When provided without units, bytes will be assumed.') -parser.add_argument('--n-gpu-layers', type=int, default=0, help='Number of layers to offload to the GPU.') -parser.add_argument('--n_ctx', type=int, default=2048, help='Size of the prompt context.') -parser.add_argument('--llama_cpp_seed', type=int, default=0, help='Seed for llama-cpp models. Default 0 (random)') - -# GPTQ -parser.add_argument('--wbits', type=int, default=0, help='Load a pre-quantized model with specified precision in bits. 2, 3, 4 and 8 are supported.') -parser.add_argument('--model_type', type=str, help='Model type of pre-quantized model. Currently LLaMA, OPT, and GPT-J are supported.') -parser.add_argument('--groupsize', type=int, default=-1, help='Group size.') -parser.add_argument('--pre_layer', type=int, nargs="+", help='The number of layers to allocate to the GPU. Setting this parameter enables CPU offloading for 4-bit models. For multi-gpu, write the numbers separated by spaces, eg --pre_layer 30 60.') -parser.add_argument('--checkpoint', type=str, help='The path to the quantized checkpoint file. If not specified, it will be automatically detected.') -parser.add_argument('--monkey-patch', action='store_true', help='Apply the monkey patch for using LoRAs with quantized models.') -parser.add_argument('--quant_attn', action='store_true', help='(triton) Enable quant attention.') -parser.add_argument('--warmup_autotune', action='store_true', help='(triton) Enable warmup autotune.') -parser.add_argument('--fused_mlp', action='store_true', help='(triton) Enable fused mlp.') - -# AutoGPTQ -parser.add_argument('--gptq-for-llama', action='store_true', help='DEPRECATED') -parser.add_argument('--autogptq', action='store_true', help='DEPRECATED') -parser.add_argument('--triton', action='store_true', help='Use triton.') -parser.add_argument('--no_inject_fused_attention', action='store_true', help='Do not use fused attention (lowers VRAM requirements).') -parser.add_argument('--no_inject_fused_mlp', action='store_true', help='Triton mode only: Do not use fused MLP (lowers VRAM requirements).') -parser.add_argument('--no_use_cuda_fp16', action='store_true', help='This can make models faster on some systems.') -parser.add_argument('--desc_act', action='store_true', help='For models that don\'t have a quantize_config.json, this parameter is used to define whether to set desc_act or not in BaseQuantizeConfig.') - -# ExLlama -parser.add_argument('--gpu-split', type=str, help="Comma-separated list of VRAM (in GB) to use per GPU device for model layers, e.g. 20,7,7") -parser.add_argument('--max_seq_len', type=int, default=2048, help="Maximum sequence length.") -parser.add_argument('--compress_pos_emb', type=int, default=1, help="Positional embeddings compression factor. Should typically be set to max_seq_len / 2048.") - -# FlexGen -parser.add_argument('--flexgen', action='store_true', help='DEPRECATED') -parser.add_argument('--percent', type=int, nargs="+", default=[0, 100, 100, 0, 100, 0], help='FlexGen: allocation percentages. Must be 6 numbers separated by spaces (default: 0, 100, 100, 0, 100, 0).') -parser.add_argument("--compress-weight", action="store_true", help="FlexGen: activate weight compression.") -parser.add_argument("--pin-weight", type=str2bool, nargs="?", const=True, default=True, help="FlexGen: whether to pin weights (setting this to False reduces CPU memory by 20%%).") - -# DeepSpeed -parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.') -parser.add_argument('--nvme-offload-dir', type=str, help='DeepSpeed: Directory to use for ZeRO-3 NVME offloading.') -parser.add_argument('--local_rank', type=int, default=0, help='DeepSpeed: Optional argument for distributed setups.') - -# RWKV -parser.add_argument('--rwkv-strategy', type=str, default=None, help='RWKV: The strategy to use while loading the model. Examples: "cpu fp32", "cuda fp16", "cuda fp16i8".') -parser.add_argument('--rwkv-cuda-on', action='store_true', help='RWKV: Compile the CUDA kernel for better performance.') - -# Gradio -parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.') -parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.') -parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.') -parser.add_argument('--share', action='store_true', help='Create a public URL. This is useful for running the web UI on Google Colab or similar.') -parser.add_argument('--auto-launch', action='store_true', default=False, help='Open the web UI in the default browser upon launch.') -parser.add_argument("--gradio-auth", type=str, help='set gradio authentication like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3"', default=None) -parser.add_argument("--gradio-auth-path", type=str, help='Set the gradio authentication file path. The file should contain one or more user:password pairs in this format: "u1:p1,u2:p2,u3:p3"', default=None) - -# API -parser.add_argument('--api', action='store_true', help='Enable the API extension.') -parser.add_argument('--api-blocking-port', type=int, default=5000, help='The listening port for the blocking API.') -parser.add_argument('--api-streaming-port', type=int, default=5005, help='The listening port for the streaming API.') -parser.add_argument('--public-api', action='store_true', help='Create a public URL for the API using Cloudfare.') - -# Multimodal -parser.add_argument('--multimodal-pipeline', type=str, default=None, help='The multimodal pipeline to use. Examples: llava-7b, llava-13b.') - -args = parser.parse_args() -args_defaults = parser.parse_args([]) - -# Deprecation warnings -if args.autogptq: - logger.warning('--autogptq has been deprecated and will be removed soon. Use --loader autogptq instead.') - args.loader = 'autogptq' -if args.gptq_for_llama: - logger.warning('--gptq-for-llama has been deprecated and will be removed soon. Use --loader gptq-for-llama instead.') - args.loader = 'gptq-for-llama' -if args.flexgen: - logger.warning('--flexgen has been deprecated and will be removed soon. Use --loader flexgen instead.') - args.loader = 'FlexGen' - -# Security warnings -if args.trust_remote_code: - logger.warning("trust_remote_code is enabled. This is dangerous.") -if args.share: - logger.warning("The gradio \"share link\" feature uses a proprietary executable to create a reverse tunnel. Use it with care.") - - -def fix_loader_name(name): - name = name.lower() - if name in ['llamacpp', 'llama.cpp', 'llama-cpp', 'llama cpp']: - return 'llama.cpp' - elif name in ['transformers', 'huggingface', 'hf', 'hugging_face', 'hugging face']: - return 'Transformers' - elif name in ['autogptq', 'auto-gptq', 'auto_gptq', 'auto gptq']: - return 'AutoGPTQ' - elif name in ['gptq-for-llama', 'gptqforllama', 'gptqllama', 'gptq for llama', 'gptq_for_llama']: - return 'GPTQ-for-LLaMa' - elif name in ['exllama', 'ex-llama', 'ex_llama', 'exlama']: - return 'ExLlama' - elif name in ['exllama-hf', 'exllama_hf', 'exllama hf', 'ex-llama-hf', 'ex_llama_hf']: - return 'ExLlama_HF' - - -if args.loader is not None: - args.loader = fix_loader_name(args.loader) - - -def add_extension(name): - if args.extensions is None: - args.extensions = [name] - elif 'api' not in args.extensions: - args.extensions.append(name) - - -# Activating the API extension -if args.api or args.public_api: - add_extension('api') - -# Activating the multimodal extension -if args.multimodal_pipeline is not None: - add_extension('multimodal') - - -def is_chat(): - return args.chat - - -# Loading model-specific settings -with Path(f'{args.model_dir}/config.yaml') as p: - if p.exists(): - model_config = yaml.safe_load(open(p, 'r').read()) - else: - model_config = {} - -# Applying user-defined model settings -with Path(f'{args.model_dir}/config-user.yaml') as p: - if p.exists(): - user_config = yaml.safe_load(open(p, 'r').read()) - for k in user_config: - if k in model_config: - model_config[k].update(user_config[k]) - else: - model_config[k] = user_config[k] - -model_config = OrderedDict(model_config) diff --git a/spaces/yeqingmei123/face-test/e4e/scripts/inference.py b/spaces/yeqingmei123/face-test/e4e/scripts/inference.py deleted file mode 100644 index 185b9b34db85dcd97b9793bd5dbfc9d1ca046549..0000000000000000000000000000000000000000 --- a/spaces/yeqingmei123/face-test/e4e/scripts/inference.py +++ /dev/null @@ -1,133 +0,0 @@ -import argparse - -import torch -import numpy as np -import sys -import os -import dlib - -sys.path.append(".") -sys.path.append("..") - -from configs import data_configs, paths_config -from datasets.inference_dataset import InferenceDataset -from torch.utils.data import DataLoader -from utils.model_utils import setup_model -from utils.common import tensor2im -from utils.alignment import align_face -from PIL import Image - - -def main(args): - net, opts = setup_model(args.ckpt, device) - is_cars = 'cars_' in opts.dataset_type - generator = net.decoder - generator.eval() - args, data_loader = setup_data_loader(args, opts) - - # Check if latents exist - latents_file_path = os.path.join(args.save_dir, 'latents.pt') - if os.path.exists(latents_file_path): - latent_codes = torch.load(latents_file_path).to(device) - else: - latent_codes = get_all_latents(net, data_loader, args.n_sample, is_cars=is_cars) - torch.save(latent_codes, latents_file_path) - - if not args.latents_only: - generate_inversions(args, generator, latent_codes, is_cars=is_cars) - - -def setup_data_loader(args, opts): - dataset_args = data_configs.DATASETS[opts.dataset_type] - transforms_dict = dataset_args['transforms'](opts).get_transforms() - images_path = args.images_dir if args.images_dir is not None else dataset_args['test_source_root'] - print(f"images path: {images_path}") - align_function = None - if args.align: - align_function = run_alignment - test_dataset = InferenceDataset(root=images_path, - transform=transforms_dict['transform_test'], - preprocess=align_function, - opts=opts) - - data_loader = DataLoader(test_dataset, - batch_size=args.batch, - shuffle=False, - num_workers=2, - drop_last=True) - - print(f'dataset length: {len(test_dataset)}') - - if args.n_sample is None: - args.n_sample = len(test_dataset) - return args, data_loader - - -def get_latents(net, x, is_cars=False): - codes = net.encoder(x) - if net.opts.start_from_latent_avg: - if codes.ndim == 2: - codes = codes + net.latent_avg.repeat(codes.shape[0], 1, 1)[:, 0, :] - else: - codes = codes + net.latent_avg.repeat(codes.shape[0], 1, 1) - if codes.shape[1] == 18 and is_cars: - codes = codes[:, :16, :] - return codes - - -def get_all_latents(net, data_loader, n_images=None, is_cars=False): - all_latents = [] - i = 0 - with torch.no_grad(): - for batch in data_loader: - if n_images is not None and i > n_images: - break - x = batch - inputs = x.to(device).float() - latents = get_latents(net, inputs, is_cars) - all_latents.append(latents) - i += len(latents) - return torch.cat(all_latents) - - -def save_image(img, save_dir, idx): - result = tensor2im(img) - im_save_path = os.path.join(save_dir, f"{idx:05d}.jpg") - Image.fromarray(np.array(result)).save(im_save_path) - - -@torch.no_grad() -def generate_inversions(args, g, latent_codes, is_cars): - print('Saving inversion images') - inversions_directory_path = os.path.join(args.save_dir, 'inversions') - os.makedirs(inversions_directory_path, exist_ok=True) - for i in range(args.n_sample): - imgs, _ = g([latent_codes[i].unsqueeze(0)], input_is_latent=True, randomize_noise=False, return_latents=True) - if is_cars: - imgs = imgs[:, :, 64:448, :] - save_image(imgs[0], inversions_directory_path, i + 1) - - -def run_alignment(image_path): - predictor = dlib.shape_predictor(paths_config.model_paths['shape_predictor']) - aligned_image = align_face(filepath=image_path, predictor=predictor) - print("Aligned image has shape: {}".format(aligned_image.size)) - return aligned_image - - -if __name__ == "__main__": - device = "cuda" - - parser = argparse.ArgumentParser(description="Inference") - parser.add_argument("--images_dir", type=str, default=None, - help="The directory of the images to be inverted") - parser.add_argument("--save_dir", type=str, default=None, - help="The directory to save the latent codes and inversion images. (default: images_dir") - parser.add_argument("--batch", type=int, default=1, help="batch size for the generator") - parser.add_argument("--n_sample", type=int, default=None, help="number of the samples to infer.") - parser.add_argument("--latents_only", action="store_true", help="infer only the latent codes of the directory") - parser.add_argument("--align", action="store_true", help="align face images before inference") - parser.add_argument("ckpt", metavar="CHECKPOINT", help="path to generator checkpoint") - - args = parser.parse_args() - main(args) diff --git a/spaces/yerfor/SyntaSpeech/utils/audio/pitch_extractors.py b/spaces/yerfor/SyntaSpeech/utils/audio/pitch_extractors.py deleted file mode 100644 index eb19c50d55d198157b2e6adedd8a343d9c363395..0000000000000000000000000000000000000000 --- a/spaces/yerfor/SyntaSpeech/utils/audio/pitch_extractors.py +++ /dev/null @@ -1,40 +0,0 @@ -import numpy as np - -PITCH_EXTRACTOR = {} - - -def register_pitch_extractor(name): - def register_pitch_extractor_(cls): - PITCH_EXTRACTOR[name] = cls - return cls - - return register_pitch_extractor_ - - -def get_pitch_extractor(name): - return PITCH_EXTRACTOR[name] - - -def extract_pitch_simple(wav): - from utils.commons.hparams import hparams - return extract_pitch(hparams['pitch_extractor'], wav, - hparams['hop_size'], hparams['audio_sample_rate'], - f0_min=hparams['f0_min'], f0_max=hparams['f0_max']) - - -def extract_pitch(extractor_name, wav_data, hop_size, audio_sample_rate, f0_min=75, f0_max=800, **kwargs): - return get_pitch_extractor(extractor_name)(wav_data, hop_size, audio_sample_rate, f0_min, f0_max, **kwargs) - - -@register_pitch_extractor('parselmouth') -def parselmouth_pitch(wav_data, hop_size, audio_sample_rate, f0_min, f0_max, - voicing_threshold=0.6, *args, **kwargs): - import parselmouth - time_step = hop_size / audio_sample_rate * 1000 - n_mel_frames = int(len(wav_data) // hop_size) - f0_pm = parselmouth.Sound(wav_data, audio_sample_rate).to_pitch_ac( - time_step=time_step / 1000, voicing_threshold=voicing_threshold, - pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency'] - pad_size = (n_mel_frames - len(f0_pm) + 1) // 2 - f0 = np.pad(f0_pm, [[pad_size, n_mel_frames - len(f0_pm) - pad_size]], mode='constant') - return f0 diff --git a/spaces/ygangang/VToonify/vtoonify/model/stylegan/op/fused_act.py b/spaces/ygangang/VToonify/vtoonify/model/stylegan/op/fused_act.py deleted file mode 100644 index 74815adafbf7a37d5d4def41ac60dbdeefdbff30..0000000000000000000000000000000000000000 --- a/spaces/ygangang/VToonify/vtoonify/model/stylegan/op/fused_act.py +++ /dev/null @@ -1,34 +0,0 @@ -import torch -from torch import nn -from torch.nn import functional as F - - -class FusedLeakyReLU(nn.Module): - def __init__(self, channel, bias=True, negative_slope=0.2, scale=2 ** 0.5): - super().__init__() - - if bias: - self.bias = nn.Parameter(torch.zeros(channel)) - - else: - self.bias = None - - self.negative_slope = negative_slope - self.scale = scale - - def forward(self, inputs): - return fused_leaky_relu(inputs, self.bias, self.negative_slope, self.scale) - - -def fused_leaky_relu(inputs, bias=None, negative_slope=0.2, scale=2 ** 0.5): - if bias is not None: - rest_dim = [1] * (inputs.ndim - bias.ndim - 1) - return ( - F.leaky_relu( - inputs + bias.view(1, bias.shape[0], *rest_dim), negative_slope=negative_slope - ) - * scale - ) - - else: - return F.leaky_relu(inputs, negative_slope=negative_slope) * scale \ No newline at end of file diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/align/convert_align_tf_to_hf.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/align/convert_align_tf_to_hf.py deleted file mode 100644 index 96e9810797690484b7d0eac82daf09d23df20871..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/align/convert_align_tf_to_hf.py +++ /dev/null @@ -1,389 +0,0 @@ -# coding=utf-8 -# Copyright 2023 The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Convert ALIGN checkpoints from the original repository.""" - -import argparse -import os - -import align -import numpy as np -import requests -import tensorflow as tf -import torch -from PIL import Image -from tokenizer import Tokenizer - -from transformers import ( - AlignConfig, - AlignModel, - AlignProcessor, - BertConfig, - BertTokenizer, - EfficientNetConfig, - EfficientNetImageProcessor, -) -from transformers.utils import logging - - -logging.set_verbosity_info() -logger = logging.get_logger(__name__) - - -def preprocess(image): - image = tf.image.resize(image, (346, 346)) - image = tf.image.crop_to_bounding_box(image, (346 - 289) // 2, (346 - 289) // 2, 289, 289) - return image - - -def get_align_config(): - vision_config = EfficientNetConfig.from_pretrained("google/efficientnet-b7") - vision_config.image_size = 289 - vision_config.hidden_dim = 640 - vision_config.id2label = {"0": "LABEL_0", "1": "LABEL_1"} - vision_config.label2id = {"LABEL_0": 0, "LABEL_1": 1} - vision_config.depthwise_padding = [] - - text_config = BertConfig() - config = AlignConfig.from_text_vision_configs( - text_config=text_config, vision_config=vision_config, projection_dim=640 - ) - return config - - -# We will verify our results on an image of cute cats -def prepare_img(): - url = "http://images.cocodataset.org/val2017/000000039769.jpg" - im = Image.open(requests.get(url, stream=True).raw) - return im - - -def get_processor(): - image_processor = EfficientNetImageProcessor( - do_center_crop=True, - rescale_factor=1 / 127.5, - rescale_offset=True, - do_normalize=False, - include_top=False, - resample=Image.BILINEAR, - ) - tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") - tokenizer.model_max_length = 64 - processor = AlignProcessor(image_processor=image_processor, tokenizer=tokenizer) - return processor - - -# here we list all keys to be renamed (original name on the left, our name on the right) -def rename_keys(original_param_names): - # EfficientNet image encoder - block_names = [v.split("_")[0].split("block")[1] for v in original_param_names if v.startswith("block")] - block_names = list(set(block_names)) - block_names = sorted(block_names) - num_blocks = len(block_names) - block_name_mapping = {b: str(i) for b, i in zip(block_names, range(num_blocks))} - - rename_keys = [] - rename_keys.append(("stem_conv/kernel:0", "embeddings.convolution.weight")) - rename_keys.append(("stem_bn/gamma:0", "embeddings.batchnorm.weight")) - rename_keys.append(("stem_bn/beta:0", "embeddings.batchnorm.bias")) - rename_keys.append(("stem_bn/moving_mean:0", "embeddings.batchnorm.running_mean")) - rename_keys.append(("stem_bn/moving_variance:0", "embeddings.batchnorm.running_var")) - - for b in block_names: - hf_b = block_name_mapping[b] - rename_keys.append((f"block{b}_expand_conv/kernel:0", f"encoder.blocks.{hf_b}.expansion.expand_conv.weight")) - rename_keys.append((f"block{b}_expand_bn/gamma:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.weight")) - rename_keys.append((f"block{b}_expand_bn/beta:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.bias")) - rename_keys.append( - (f"block{b}_expand_bn/moving_mean:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean") - ) - rename_keys.append( - (f"block{b}_expand_bn/moving_variance:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_var") - ) - rename_keys.append( - (f"block{b}_dwconv/depthwise_kernel:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight") - ) - rename_keys.append((f"block{b}_bn/gamma:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight")) - rename_keys.append((f"block{b}_bn/beta:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias")) - rename_keys.append( - (f"block{b}_bn/moving_mean:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean") - ) - rename_keys.append( - (f"block{b}_bn/moving_variance:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var") - ) - - rename_keys.append((f"block{b}_se_reduce/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight")) - rename_keys.append((f"block{b}_se_reduce/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias")) - rename_keys.append((f"block{b}_se_expand/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.weight")) - rename_keys.append((f"block{b}_se_expand/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.bias")) - rename_keys.append( - (f"block{b}_project_conv/kernel:0", f"encoder.blocks.{hf_b}.projection.project_conv.weight") - ) - rename_keys.append((f"block{b}_project_bn/gamma:0", f"encoder.blocks.{hf_b}.projection.project_bn.weight")) - rename_keys.append((f"block{b}_project_bn/beta:0", f"encoder.blocks.{hf_b}.projection.project_bn.bias")) - rename_keys.append( - (f"block{b}_project_bn/moving_mean:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_mean") - ) - rename_keys.append( - (f"block{b}_project_bn/moving_variance:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_var") - ) - - key_mapping = {} - for item in rename_keys: - if item[0] in original_param_names: - key_mapping[item[0]] = "vision_model." + item[1] - - # BERT text encoder - rename_keys = [] - old = "tf_bert_model/bert" - new = "text_model" - for i in range(12): - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/self/query/kernel:0", - f"{new}.encoder.layer.{i}.attention.self.query.weight", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/self/query/bias:0", - f"{new}.encoder.layer.{i}.attention.self.query.bias", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/self/key/kernel:0", - f"{new}.encoder.layer.{i}.attention.self.key.weight", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/self/key/bias:0", - f"{new}.encoder.layer.{i}.attention.self.key.bias", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/self/value/kernel:0", - f"{new}.encoder.layer.{i}.attention.self.value.weight", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/self/value/bias:0", - f"{new}.encoder.layer.{i}.attention.self.value.bias", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/output/dense/kernel:0", - f"{new}.encoder.layer.{i}.attention.output.dense.weight", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/output/dense/bias:0", - f"{new}.encoder.layer.{i}.attention.output.dense.bias", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0", - f"{new}.encoder.layer.{i}.attention.output.LayerNorm.weight", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0", - f"{new}.encoder.layer.{i}.attention.output.LayerNorm.bias", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/intermediate/dense/kernel:0", - f"{new}.encoder.layer.{i}.intermediate.dense.weight", - ) - ) - rename_keys.append( - ( - f"{old}/encoder/layer_._{i}/intermediate/dense/bias:0", - f"{new}.encoder.layer.{i}.intermediate.dense.bias", - ) - ) - rename_keys.append( - (f"{old}/encoder/layer_._{i}/output/dense/kernel:0", f"{new}.encoder.layer.{i}.output.dense.weight") - ) - rename_keys.append( - (f"{old}/encoder/layer_._{i}/output/dense/bias:0", f"{new}.encoder.layer.{i}.output.dense.bias") - ) - rename_keys.append( - (f"{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0", f"{new}.encoder.layer.{i}.output.LayerNorm.weight") - ) - rename_keys.append( - (f"{old}/encoder/layer_._{i}/output/LayerNorm/beta:0", f"{new}.encoder.layer.{i}.output.LayerNorm.bias") - ) - - rename_keys.append((f"{old}/embeddings/word_embeddings/weight:0", f"{new}.embeddings.word_embeddings.weight")) - rename_keys.append( - (f"{old}/embeddings/position_embeddings/embeddings:0", f"{new}.embeddings.position_embeddings.weight") - ) - rename_keys.append( - (f"{old}/embeddings/token_type_embeddings/embeddings:0", f"{new}.embeddings.token_type_embeddings.weight") - ) - rename_keys.append((f"{old}/embeddings/LayerNorm/gamma:0", f"{new}.embeddings.LayerNorm.weight")) - rename_keys.append((f"{old}/embeddings/LayerNorm/beta:0", f"{new}.embeddings.LayerNorm.bias")) - - rename_keys.append((f"{old}/pooler/dense/kernel:0", f"{new}.pooler.dense.weight")) - rename_keys.append((f"{old}/pooler/dense/bias:0", f"{new}.pooler.dense.bias")) - rename_keys.append(("dense/kernel:0", "text_projection.weight")) - rename_keys.append(("dense/bias:0", "text_projection.bias")) - rename_keys.append(("dense/bias:0", "text_projection.bias")) - rename_keys.append(("temperature:0", "temperature")) - - for item in rename_keys: - if item[0] in original_param_names: - key_mapping[item[0]] = item[1] - return key_mapping - - -def replace_params(hf_params, tf_params, key_mapping): - list(hf_params.keys()) - - for key, value in tf_params.items(): - if key not in key_mapping: - continue - - hf_key = key_mapping[key] - if "_conv" in key and "kernel" in key: - new_hf_value = torch.from_numpy(value).permute(3, 2, 0, 1) - elif "embeddings" in key: - new_hf_value = torch.from_numpy(value) - elif "depthwise_kernel" in key: - new_hf_value = torch.from_numpy(value).permute(2, 3, 0, 1) - elif "kernel" in key: - new_hf_value = torch.from_numpy(np.transpose(value)) - elif "temperature" in key: - new_hf_value = value - elif "bn/gamma" or "bn/beta" in key: - new_hf_value = torch.from_numpy(np.transpose(value)).squeeze() - else: - new_hf_value = torch.from_numpy(value) - - # Replace HF parameters with original TF model parameters - hf_params[hf_key].copy_(new_hf_value) - - -@torch.no_grad() -def convert_align_checkpoint(checkpoint_path, pytorch_dump_folder_path, save_model, push_to_hub): - """ - Copy/paste/tweak model's weights to our ALIGN structure. - """ - # Load original model - seq_length = 64 - tok = Tokenizer(seq_length) - original_model = align.Align("efficientnet-b7", "bert-base", 640, seq_length, tok.get_vocab_size()) - original_model.compile() - original_model.load_weights(checkpoint_path) - - tf_params = original_model.trainable_variables - tf_non_train_params = original_model.non_trainable_variables - tf_params = {param.name: param.numpy() for param in tf_params} - for param in tf_non_train_params: - tf_params[param.name] = param.numpy() - tf_param_names = list(tf_params.keys()) - - # Load HuggingFace model - config = get_align_config() - hf_model = AlignModel(config).eval() - hf_params = hf_model.state_dict() - - # Create src-to-dst parameter name mapping dictionary - print("Converting parameters...") - key_mapping = rename_keys(tf_param_names) - replace_params(hf_params, tf_params, key_mapping) - - # Initialize processor - processor = get_processor() - inputs = processor( - images=prepare_img(), text="A picture of a cat", padding="max_length", max_length=64, return_tensors="pt" - ) - - # HF model inference - hf_model.eval() - with torch.no_grad(): - outputs = hf_model(**inputs) - - hf_image_features = outputs.image_embeds.detach().numpy() - hf_text_features = outputs.text_embeds.detach().numpy() - - # Original model inference - original_model.trainable = False - tf_image_processor = EfficientNetImageProcessor( - do_center_crop=True, - do_rescale=False, - do_normalize=False, - include_top=False, - resample=Image.BILINEAR, - ) - image = tf_image_processor(images=prepare_img(), return_tensors="tf", data_format="channels_last")["pixel_values"] - text = tok(tf.constant(["A picture of a cat"])) - - image_features = original_model.image_encoder(image, training=False) - text_features = original_model.text_encoder(text, training=False) - - image_features = tf.nn.l2_normalize(image_features, axis=-1) - text_features = tf.nn.l2_normalize(text_features, axis=-1) - - # Check whether original and HF model outputs match -> np.allclose - if not np.allclose(image_features, hf_image_features, atol=1e-3): - raise ValueError("The predicted image features are not the same.") - if not np.allclose(text_features, hf_text_features, atol=1e-3): - raise ValueError("The predicted text features are not the same.") - print("Model outputs match!") - - if save_model: - # Create folder to save model - if not os.path.isdir(pytorch_dump_folder_path): - os.mkdir(pytorch_dump_folder_path) - # Save converted model and image processor - hf_model.save_pretrained(pytorch_dump_folder_path) - processor.save_pretrained(pytorch_dump_folder_path) - - if push_to_hub: - # Push model and image processor to hub - print("Pushing converted ALIGN to the hub...") - processor.push_to_hub("align-base") - hf_model.push_to_hub("align-base") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - # Required parameters - parser.add_argument( - "--checkpoint_path", - default="./weights/model-weights", - type=str, - help="Path to the pretrained TF ALIGN checkpoint.", - ) - parser.add_argument( - "--pytorch_dump_folder_path", - default="hf_model", - type=str, - help="Path to the output PyTorch model directory.", - ) - parser.add_argument("--save_model", action="store_true", help="Save model to local") - parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") - - args = parser.parse_args() - convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/distilbert/modeling_flax_distilbert.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/distilbert/modeling_flax_distilbert.py deleted file mode 100644 index 24e2c7e3987e07b40a3fbfb8bea97886124f7587..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/distilbert/modeling_flax_distilbert.py +++ /dev/null @@ -1,894 +0,0 @@ -# coding=utf-8 -# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc. -# -# 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 math -from typing import Callable, Optional, Tuple - -import flax.linen as nn -import jax -import jax.numpy as jnp -import numpy as np -from flax.core.frozen_dict import FrozenDict, freeze, unfreeze -from flax.traverse_util import flatten_dict, unflatten_dict -from jax import lax - -from ...modeling_flax_outputs import ( - FlaxBaseModelOutput, - FlaxMaskedLMOutput, - FlaxMultipleChoiceModelOutput, - FlaxQuestionAnsweringModelOutput, - FlaxSequenceClassifierOutput, - FlaxTokenClassifierOutput, -) -from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring, overwrite_call_docstring -from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging -from .configuration_distilbert import DistilBertConfig - - -logger = logging.get_logger(__name__) - -_CHECKPOINT_FOR_DOC = "distilbert-base-uncased" -_CONFIG_FOR_DOC = "DistilBertConfig" - - -FLAX_DISTILBERT_START_DOCSTRING = r""" - - This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the - library implements for all its model (such as downloading, saving and converting weights from PyTorch models) - - This model is also a Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module) - subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to - general usage and behavior. - - Finally, this model supports inherent JAX features such as: - - - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit) - - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation) - - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap) - - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap) - - Parameters: - config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model. - Initializing with a config file does not load the weights associated with the model, only the - configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. -""" - -DISTILBERT_INPUTS_DOCSTRING = r""" - Args: - input_ids (`numpy.ndarray` of shape `({0})`): - Indices of input sequence tokens in the vocabulary. - - Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and - [`PreTrainedTokenizer.__call__`] for details. - - [What are input IDs?](../glossary#input-ids) - attention_mask (`numpy.ndarray` of shape `({0})`, *optional*): - Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned - tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for - more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. -""" - - -def get_angles(pos, i, d_model): - angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model)) - return pos * angle_rates - - -def positional_encoding(position, d_model): - # create the sinusoidal pattern for the positional encoding - angle_rads = get_angles(np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model) - - # apply sin to even indices in the array; 2i - angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2]) - - # apply cos to odd indices in the array; 2i+1 - angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2]) - - pos_encoding = angle_rads[np.newaxis, ...] - - return jnp.array(pos_encoding) - - -class FlaxEmbeddings(nn.Module): - """Construct the embeddings from word, position and token_type embeddings.""" - - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.word_embeddings = nn.Embed( - self.config.vocab_size, - self.config.dim, - embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - if not self.config.sinusoidal_pos_embds: - self.position_embeddings = nn.Embed( - self.config.max_position_embeddings, - self.config.dim, - embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - else: - self.pos_encoding = positional_encoding(self.config.max_position_embeddings, self.config.dim) - self.LayerNorm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype) - self.dropout = nn.Dropout(rate=self.config.dropout) - - def __call__(self, input_ids, deterministic: bool = True): - # Embed - batch_size, seq_length = input_ids.shape - inputs_embeds = self.word_embeddings(input_ids.astype("i4")) - if not self.config.sinusoidal_pos_embds: - position_ids = jnp.arange(seq_length).astype("i4") - position_ids = jnp.broadcast_to(position_ids, shape=(batch_size, seq_length)) - position_embeds = self.position_embeddings(position_ids.astype("i4")) - else: - position_embeds = self.pos_encoding[:, :seq_length, :] - # explictly cast the positions here, since self.embed_positions are not registered as parameters - position_embeds = position_embeds.astype(inputs_embeds.dtype) - - # Sum all embeddings - hidden_states = inputs_embeds + position_embeds - - # Layer Norm - hidden_states = self.LayerNorm(hidden_states) - hidden_states = self.dropout(hidden_states, deterministic=deterministic) - return hidden_states - - -class FlaxMultiHeadSelfAttention(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.n_heads = self.config.n_heads - self.dim = self.config.dim - self.dropout = nn.Dropout(rate=self.config.attention_dropout) - - if not (self.dim % self.n_heads == 0): - raise ValueError(f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}") - - self.q_lin = nn.Dense( - self.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.k_lin = nn.Dense( - self.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.v_lin = nn.Dense( - self.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.out_lin = nn.Dense( - self.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - - def __call__( - self, - query, - key, - value, - mask, - deterministic: bool = True, - output_attentions: bool = False, - ): - bs, q_len, dim = query.shape - k_len = key.shape[1] - # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured' - # assert key.size() == value.size() - - dim_per_head = self.dim // self.n_heads - - mask_reshp = (bs, 1, 1, k_len) - - def shape(x): - """separate heads""" - return x.reshape(bs, -1, self.n_heads, dim_per_head).transpose(0, 2, 1, 3) - - def unshape(x): - """group heads""" - return x.transpose(0, 2, 1, 3).reshape(bs, -1, self.n_heads * dim_per_head) - - q = shape(self.q_lin(query)) # (bs, n_heads, q_len, dim_per_head) - k = shape(self.k_lin(key)) # (bs, n_heads, k_len, dim_per_head) - v = shape(self.v_lin(value)) # (bs, n_heads, k_len, dim_per_head) - - q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_len, dim_per_head) - scores = jnp.matmul(q, k.transpose(0, 1, 3, 2)) # (bs, n_heads, q_len, k_len) - mask = jnp.reshape(mask, mask_reshp) - - mask = mask.astype(scores.dtype) - scores = scores - 1e30 * (1.0 - mask) - - weights = nn.softmax(scores, axis=-1) # (bs, n_heads, q_len, k_len) - weights = self.dropout(weights, deterministic=deterministic) - - context = jnp.matmul(weights, v) # (bs, n_heads, q_len, dim_per_head) - context = unshape(context) # (bs, q_len, dim) - context = self.out_lin(context) # (bs, q_len, dim) - - if output_attentions: - return (context, weights) - else: - return (context,) - - -class FlaxFFN(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.dropout = nn.Dropout(rate=self.config.dropout) - self.chunk_size_feed_forward = self.config.chunk_size_feed_forward - self.seq_len_dim = 1 - self.lin1 = nn.Dense( - self.config.hidden_dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.lin2 = nn.Dense( - self.config.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - - self.activation = ACT2FN[self.config.activation] - - def __call__(self, hidden_states, deterministic: bool = True): - hidden_states = self.lin1(hidden_states) - hidden_states = self.activation(hidden_states) - hidden_states = self.lin2(hidden_states) - hidden_states = self.dropout(hidden_states, deterministic=deterministic) - return hidden_states - - -class FlaxTransformerBlock(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - assert ( - self.config.dim % self.config.n_heads == 0 - ), f"Hidden size {self.config.dim} not dividable by number of heads {self.config.n_heads}" - - self.attention = FlaxMultiHeadSelfAttention(self.config, dtype=self.dtype) - self.sa_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype) - - self.ffn = FlaxFFN(self.config, dtype=self.dtype) - self.output_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype) - - def __call__( - self, - hidden_states, - attn_mask, - output_attentions: bool = False, - deterministic: bool = True, - ): - # Self-Attention - sa_output = self.attention( - query=hidden_states, - key=hidden_states, - value=hidden_states, - mask=attn_mask, - output_attentions=output_attentions, - deterministic=deterministic, - ) - if output_attentions: - sa_output, sa_weights = sa_output - else: - assert type(sa_output) == tuple - sa_output = sa_output[0] - sa_output = self.sa_layer_norm(sa_output + hidden_states) - - # Feed Forward Network - ffn_output = self.ffn(sa_output, deterministic=deterministic) - ffn_output = self.output_layer_norm(ffn_output + sa_output) - output = (ffn_output,) - if output_attentions: - output = (sa_weights,) + output - return output - - -class FlaxTransformer(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.layers = [ - FlaxTransformerBlock(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.n_layers) - ] - - def __call__( - self, - hidden_states, - attention_mask, - output_attentions: bool = False, - output_hidden_states: bool = False, - deterministic: bool = True, - return_dict: bool = False, - ): - all_hidden_states = () if output_hidden_states else None - all_attentions = () if output_attentions else None - - for layer_module in self.layers: - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - layer_outputs = layer_module( - hidden_states=hidden_states, - attn_mask=attention_mask, - output_attentions=output_attentions, - deterministic=deterministic, - ) - hidden_states = layer_outputs[-1] - - if output_attentions: - assert len(layer_outputs) == 2 - attentions = layer_outputs[0] - all_attentions = all_attentions + (attentions,) - else: - assert len(layer_outputs) == 1 - - # Add last layer - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - if not return_dict: - return tuple(v for v in [hidden_states, all_attentions, all_hidden_states] if v is not None) - return FlaxBaseModelOutput( - last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions - ) - - -class FlaxTransformerEncoder(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.layer = FlaxTransformer(self.config, dtype=self.dtype) - - def __call__( - self, - hidden_states, - attention_mask, - output_attentions: bool = False, - output_hidden_states: bool = False, - deterministic: bool = True, - return_dict: bool = False, - ): - return self.layer( - hidden_states=hidden_states, - attention_mask=attention_mask, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - deterministic=deterministic, - return_dict=return_dict, - ) - - -class FlaxDistilBertLMDecoder(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros - - def setup(self): - self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,)) - - def __call__(self, inputs, kernel): - inputs = jnp.asarray(inputs, self.dtype) - kernel = jnp.asarray(kernel, self.dtype) - y = lax.dot_general(inputs, kernel, (((inputs.ndim - 1,), (0,)), ((), ()))) - bias = jnp.asarray(self.bias, self.dtype) - y = y + bias - return y - - -class FlaxDistilBertPreTrainedModel(FlaxPreTrainedModel): - """ - An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained - models. - """ - - config_class = DistilBertConfig - base_model_prefix = "distilbert" - module_class: nn.Module = None - - def __init__( - self, - config: DistilBertConfig, - input_shape: Tuple = (1, 1), - seed: int = 0, - dtype: jnp.dtype = jnp.float32, - _do_init: bool = True, - **kwargs, - ): - module = self.module_class(config=config, dtype=dtype, **kwargs) - super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init) - - def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict: - # init input tensors - input_ids = jnp.zeros(input_shape, dtype="i4") - attention_mask = jnp.ones_like(input_ids) - - params_rng, dropout_rng = jax.random.split(rng) - rngs = {"params": params_rng, "dropout": dropout_rng} - - random_params = self.module.init(rngs, input_ids, attention_mask, return_dict=False)["params"] - - if params is not None: - random_params = flatten_dict(unfreeze(random_params)) - params = flatten_dict(unfreeze(params)) - for missing_key in self._missing_keys: - params[missing_key] = random_params[missing_key] - self._missing_keys = set() - return freeze(unflatten_dict(params)) - else: - return random_params - - @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) - def __call__( - self, - input_ids, - attention_mask=None, - head_mask=None, - params: dict = None, - dropout_rng: jax.random.PRNGKey = None, - train: bool = False, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = 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 - ) - return_dict = return_dict if return_dict is not None else self.config.return_dict - - if attention_mask is None: - attention_mask = jnp.ones_like(input_ids) - - # Handle any PRNG if needed - rngs = {} - if dropout_rng is not None: - rngs["dropout"] = dropout_rng - - return self.module.apply( - {"params": params or self.params}, - jnp.array(input_ids, dtype="i4"), - jnp.array(attention_mask, dtype="i4"), - not train, - output_attentions, - output_hidden_states, - return_dict, - rngs=rngs, - ) - - -class FlaxDistilBertModule(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.embeddings = FlaxEmbeddings(self.config, dtype=self.dtype) - self.transformer = FlaxTransformerEncoder(self.config, dtype=self.dtype) - - def __call__( - self, - input_ids, - attention_mask, - deterministic: bool = True, - output_attentions: bool = False, - output_hidden_states: bool = False, - return_dict: bool = True, - ): - 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 - ) - return_dict = return_dict if return_dict is not None else self.config.return_dict - - input_embeds = self.embeddings(input_ids, deterministic=deterministic) - return self.transformer( - hidden_states=input_embeds, - attention_mask=attention_mask, - deterministic=deterministic, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - -@add_start_docstrings( - "The bare DistilBert Model transformer outputting raw hidden-states without any specific head on top.", - FLAX_DISTILBERT_START_DOCSTRING, -) -class FlaxDistilBertModel(FlaxDistilBertPreTrainedModel): - module_class = FlaxDistilBertModule - - -append_call_sample_docstring(FlaxDistilBertModel, _CHECKPOINT_FOR_DOC, None, _CONFIG_FOR_DOC) - - -class FlaxDistilBertForMaskedLMModule(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 # the dtype of the computation - - def setup(self): - self.distilbert = FlaxDistilBertModule(self.config, dtype=self.dtype) - self.vocab_transform = nn.Dense( - self.config.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.vocab_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype) - if self.config.tie_word_embeddings: - self.vocab_projector = FlaxDistilBertLMDecoder( - self.config, - dtype=self.dtype, - ) - else: - self.vocab_projector = nn.Dense( - self.config.vocab_size, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - - def __call__( - self, - input_ids, - attention_mask, - deterministic: bool = True, - output_attentions: bool = False, - output_hidden_states: bool = False, - return_dict: bool = True, - ): - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - dlbrt_output = self.distilbert( - input_ids=input_ids, - attention_mask=attention_mask, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - deterministic=deterministic, - return_dict=return_dict, - ) - hidden_states = dlbrt_output[0] - prediction_logits = self.vocab_transform(hidden_states) - prediction_logits = ACT2FN[self.config.activation](prediction_logits) - prediction_logits = self.vocab_layer_norm(prediction_logits) - - if self.config.tie_word_embeddings: - shared_embedding = self.distilbert.variables["params"]["embeddings"]["word_embeddings"]["embedding"] - prediction_logits = self.vocab_projector(prediction_logits, shared_embedding.T) - else: - prediction_logits = self.vocab_projector(prediction_logits) - - if not return_dict: - output = (prediction_logits,) + dlbrt_output[1:] - return output - - return FlaxMaskedLMOutput( - logits=prediction_logits, - hidden_states=dlbrt_output.hidden_states, - attentions=dlbrt_output.attentions, - ) - - -@add_start_docstrings("""DistilBert Model with a `language modeling` head on top.""", FLAX_DISTILBERT_START_DOCSTRING) -class FlaxDistilBertForMaskedLM(FlaxDistilBertPreTrainedModel): - module_class = FlaxDistilBertForMaskedLMModule - - -append_call_sample_docstring(FlaxDistilBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC) - - -class FlaxDistilBertForSequenceClassificationModule(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 - - def setup(self): - self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype) - self.pre_classifier = nn.Dense( - self.config.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout) - self.classifier = nn.Dense( - self.config.num_labels, - dtype=self.dtype, - ) - - def __call__( - self, - input_ids, - attention_mask, - deterministic: bool = True, - output_attentions: bool = False, - output_hidden_states: bool = False, - return_dict: bool = True, - ): - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - # Model - distilbert_output = self.distilbert( - input_ids, - attention_mask, - deterministic=deterministic, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - hidden_state = distilbert_output[0] # (bs, seq_len, dim) - pooled_output = hidden_state[:, 0] # (bs, dim) - pooled_output = self.pre_classifier(pooled_output) # (bs, dim) - pooled_output = ACT2FN["relu"](pooled_output) - pooled_output = self.dropout(pooled_output, deterministic=deterministic) - logits = self.classifier(pooled_output) # (bs, dim) - - if not return_dict: - return (logits,) + distilbert_output[1:] - - return FlaxSequenceClassifierOutput( - logits=logits, - hidden_states=distilbert_output.hidden_states, - attentions=distilbert_output.attentions, - ) - - -@add_start_docstrings( - """ - DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the - pooled output) e.g. for GLUE tasks. - """, - FLAX_DISTILBERT_START_DOCSTRING, -) -class FlaxDistilBertForSequenceClassification(FlaxDistilBertPreTrainedModel): - module_class = FlaxDistilBertForSequenceClassificationModule - - -append_call_sample_docstring( - FlaxDistilBertForSequenceClassification, - _CHECKPOINT_FOR_DOC, - FlaxSequenceClassifierOutput, - _CONFIG_FOR_DOC, -) - - -class FlaxDistilBertForMultipleChoiceModule(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 - - def setup(self): - self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype) - self.pre_classifier = nn.Dense( - self.config.dim, - dtype=self.dtype, - kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range), - ) - self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout) - self.classifier = nn.Dense( - 1, - dtype=self.dtype, - ) - - def __call__( - self, - input_ids, - attention_mask, - deterministic: bool = True, - output_attentions: bool = False, - output_hidden_states: bool = False, - return_dict: bool = True, - ): - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - num_choices = input_ids.shape[1] - input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None - attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None - - # Model - outputs = self.distilbert( - input_ids, - attention_mask, - deterministic=deterministic, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - hidden_state = outputs[0] - pooled_output = hidden_state[:, 0] - pooled_output = self.pre_classifier(pooled_output) - pooled_output = ACT2FN["relu"](pooled_output) - pooled_output = self.dropout(pooled_output, deterministic=deterministic) - logits = self.classifier(pooled_output) - - reshaped_logits = logits.reshape(-1, num_choices) - - if not return_dict: - return (reshaped_logits,) + outputs[2:] - - return FlaxMultipleChoiceModelOutput( - logits=reshaped_logits, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - - -@add_start_docstrings( - """ - DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and - a softmax) e.g. for RocStories/SWAG tasks. - """, - FLAX_DISTILBERT_START_DOCSTRING, -) -class FlaxDistilBertForMultipleChoice(FlaxDistilBertPreTrainedModel): - module_class = FlaxDistilBertForMultipleChoiceModule - - -overwrite_call_docstring( - FlaxDistilBertForMultipleChoice, DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length") -) -append_call_sample_docstring( - FlaxDistilBertForMultipleChoice, - _CHECKPOINT_FOR_DOC, - FlaxMultipleChoiceModelOutput, - _CONFIG_FOR_DOC, -) - - -class FlaxDistilBertForTokenClassificationModule(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 - - def setup(self): - self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype) - self.dropout = nn.Dropout(rate=self.config.dropout) - self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype) - - def __call__( - self, - input_ids, - attention_mask, - deterministic: bool = True, - output_attentions: bool = False, - output_hidden_states: bool = False, - return_dict: bool = True, - ): - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - # Model - outputs = self.distilbert( - input_ids, - attention_mask, - deterministic=deterministic, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - hidden_states = outputs[0] - hidden_states = self.dropout(hidden_states, deterministic=deterministic) - logits = self.classifier(hidden_states) - - if not return_dict: - return (logits,) + outputs[1:] - - return FlaxTokenClassifierOutput( - logits=logits, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - - -@add_start_docstrings( - """ - DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. - for Named-Entity-Recognition (NER) tasks. - """, - FLAX_DISTILBERT_START_DOCSTRING, -) -class FlaxDistilBertForTokenClassification(FlaxDistilBertPreTrainedModel): - module_class = FlaxDistilBertForTokenClassificationModule - - -append_call_sample_docstring( - FlaxDistilBertForTokenClassification, - _CHECKPOINT_FOR_DOC, - FlaxTokenClassifierOutput, - _CONFIG_FOR_DOC, -) - - -class FlaxDistilBertForQuestionAnsweringModule(nn.Module): - config: DistilBertConfig - dtype: jnp.dtype = jnp.float32 - - def setup(self): - self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype) - self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype) - assert self.config.num_labels == 2 - self.dropout = nn.Dropout(rate=self.config.qa_dropout) - - def __call__( - self, - input_ids, - attention_mask, - deterministic: bool = True, - output_attentions: bool = False, - output_hidden_states: bool = False, - return_dict: bool = True, - ): - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - # Model - distilbert_output = self.distilbert( - input_ids, - attention_mask, - deterministic=deterministic, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - hidden_states = distilbert_output[0] - - hidden_states = self.dropout(hidden_states, deterministic=deterministic) - logits = self.qa_outputs(hidden_states) - start_logits, end_logits = logits.split(self.config.num_labels, axis=-1) - start_logits = start_logits.squeeze(-1) - end_logits = end_logits.squeeze(-1) - - if not return_dict: - return (start_logits, end_logits) + distilbert_output[1:] - - return FlaxQuestionAnsweringModelOutput( - start_logits=start_logits, - end_logits=end_logits, - hidden_states=distilbert_output.hidden_states, - attentions=distilbert_output.attentions, - ) - - -@add_start_docstrings( - """ - DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a - linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). - """, - FLAX_DISTILBERT_START_DOCSTRING, -) -class FlaxDistilBertForQuestionAnswering(FlaxDistilBertPreTrainedModel): - module_class = FlaxDistilBertForQuestionAnsweringModule - - -append_call_sample_docstring( - FlaxDistilBertForQuestionAnswering, - _CHECKPOINT_FOR_DOC, - FlaxQuestionAnsweringModelOutput, - _CONFIG_FOR_DOC, -) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/lxmert/__init__.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/lxmert/__init__.py deleted file mode 100644 index 4f7e775431dd0a250dbbb5ca422f1a81be919225..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/lxmert/__init__.py +++ /dev/null @@ -1,117 +0,0 @@ -# Copyright 2020 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. - -from typing import TYPE_CHECKING - -from ...utils import ( - OptionalDependencyNotAvailable, - _LazyModule, - is_tf_available, - is_tokenizers_available, - is_torch_available, -) - - -_import_structure = { - "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"], - "tokenization_lxmert": ["LxmertTokenizer"], -} - -try: - if not is_tokenizers_available(): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - pass -else: - _import_structure["tokenization_lxmert_fast"] = ["LxmertTokenizerFast"] - -try: - if not is_torch_available(): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - pass -else: - _import_structure["modeling_lxmert"] = [ - "LxmertEncoder", - "LxmertForPreTraining", - "LxmertForQuestionAnswering", - "LxmertModel", - "LxmertPreTrainedModel", - "LxmertVisualFeatureEncoder", - "LxmertXLayer", - ] - -try: - if not is_tf_available(): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - pass -else: - _import_structure["modeling_tf_lxmert"] = [ - "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", - "TFLxmertForPreTraining", - "TFLxmertMainLayer", - "TFLxmertModel", - "TFLxmertPreTrainedModel", - "TFLxmertVisualFeatureEncoder", - ] - - -if TYPE_CHECKING: - from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig - from .tokenization_lxmert import LxmertTokenizer - - try: - if not is_tokenizers_available(): - raise OptionalDependencyNotAvailable() - except OptionalDependencyNotAvailable: - pass - else: - from .tokenization_lxmert_fast import LxmertTokenizerFast - - try: - if not is_torch_available(): - raise OptionalDependencyNotAvailable() - except OptionalDependencyNotAvailable: - pass - else: - from .modeling_lxmert import ( - LxmertEncoder, - LxmertForPreTraining, - LxmertForQuestionAnswering, - LxmertModel, - LxmertPreTrainedModel, - LxmertVisualFeatureEncoder, - LxmertXLayer, - ) - - try: - if not is_tf_available(): - raise OptionalDependencyNotAvailable() - except OptionalDependencyNotAvailable: - pass - else: - from .modeling_tf_lxmert import ( - TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, - TFLxmertForPreTraining, - TFLxmertMainLayer, - TFLxmertModel, - TFLxmertPreTrainedModel, - TFLxmertVisualFeatureEncoder, - ) - -else: - import sys - - sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/owlvit/processing_owlvit.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/owlvit/processing_owlvit.py deleted file mode 100644 index 088693a057f318cb778dfb8392a017ddd9e78e37..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/owlvit/processing_owlvit.py +++ /dev/null @@ -1,224 +0,0 @@ -# coding=utf-8 -# Copyright 2022 The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -Image/Text processor class for OWL-ViT -""" - -import warnings -from typing import List - -import numpy as np - -from ...processing_utils import ProcessorMixin -from ...tokenization_utils_base import BatchEncoding -from ...utils import is_flax_available, is_tf_available, is_torch_available - - -class OwlViTProcessor(ProcessorMixin): - r""" - Constructs an OWL-ViT processor which wraps [`OwlViTImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`] - into a single processor that interits both the image processor and tokenizer functionalities. See the - [`~OwlViTProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more information. - - Args: - image_processor ([`OwlViTImageProcessor`], *optional*): - The image processor is a required input. - tokenizer ([`CLIPTokenizer`, `CLIPTokenizerFast`], *optional*): - The tokenizer is a required input. - """ - attributes = ["image_processor", "tokenizer"] - image_processor_class = "OwlViTImageProcessor" - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast") - - def __init__(self, image_processor=None, tokenizer=None, **kwargs): - feature_extractor = None - if "feature_extractor" in kwargs: - warnings.warn( - "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" - " instead.", - FutureWarning, - ) - feature_extractor = kwargs.pop("feature_extractor") - - image_processor = image_processor if image_processor is not None else feature_extractor - if image_processor is None: - raise ValueError("You need to specify an `image_processor`.") - if tokenizer is None: - raise ValueError("You need to specify a `tokenizer`.") - - super().__init__(image_processor, tokenizer) - - def __call__(self, text=None, images=None, query_images=None, padding="max_length", return_tensors="np", **kwargs): - """ - Main method to prepare for the model one or several text(s) and image(s). This method forwards the `text` and - `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode: - the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to - CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring - of the above two methods for more information. - - Args: - text (`str`, `List[str]`, `List[List[str]]`): - The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings - (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set - `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). - images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, - `List[torch.Tensor]`): - The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch - tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a - number of channels, H and W are image height and width. - query_images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): - The query image to be prepared, one query image is expected per target image to be queried. Each image - can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image - should be of shape (C, H, W), where C is a number of channels, H and W are image height and width. - return_tensors (`str` or [`~utils.TensorType`], *optional*): - If set, will return tensors of a particular framework. Acceptable values are: - - `'tf'`: Return TensorFlow `tf.constant` objects. - - `'pt'`: Return PyTorch `torch.Tensor` objects. - - `'np'`: Return NumPy `np.ndarray` objects. - - `'jax'`: Return JAX `jnp.ndarray` objects. - Returns: - [`BatchEncoding`]: A [`BatchEncoding`] with the following fields: - - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. - - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when - `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not - `None`). - - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. - """ - - if text is None and query_images is None and images is None: - raise ValueError( - "You have to specify at least one text or query image or image. All three cannot be none." - ) - - if text is not None: - if isinstance(text, str) or (isinstance(text, List) and not isinstance(text[0], List)): - encodings = [self.tokenizer(text, padding=padding, return_tensors=return_tensors, **kwargs)] - - elif isinstance(text, List) and isinstance(text[0], List): - encodings = [] - - # Maximum number of queries across batch - max_num_queries = max([len(t) for t in text]) - - # Pad all batch samples to max number of text queries - for t in text: - if len(t) != max_num_queries: - t = t + [" "] * (max_num_queries - len(t)) - - encoding = self.tokenizer(t, padding=padding, return_tensors=return_tensors, **kwargs) - encodings.append(encoding) - else: - raise TypeError("Input text should be a string, a list of strings or a nested list of strings") - - if return_tensors == "np": - input_ids = np.concatenate([encoding["input_ids"] for encoding in encodings], axis=0) - attention_mask = np.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0) - - elif return_tensors == "jax" and is_flax_available(): - import jax.numpy as jnp - - input_ids = jnp.concatenate([encoding["input_ids"] for encoding in encodings], axis=0) - attention_mask = jnp.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0) - - elif return_tensors == "pt" and is_torch_available(): - import torch - - input_ids = torch.cat([encoding["input_ids"] for encoding in encodings], dim=0) - attention_mask = torch.cat([encoding["attention_mask"] for encoding in encodings], dim=0) - - elif return_tensors == "tf" and is_tf_available(): - import tensorflow as tf - - input_ids = tf.stack([encoding["input_ids"] for encoding in encodings], axis=0) - attention_mask = tf.stack([encoding["attention_mask"] for encoding in encodings], axis=0) - - else: - raise ValueError("Target return tensor type could not be returned") - - encoding = BatchEncoding() - encoding["input_ids"] = input_ids - encoding["attention_mask"] = attention_mask - - if query_images is not None: - encoding = BatchEncoding() - query_pixel_values = self.image_processor( - query_images, return_tensors=return_tensors, **kwargs - ).pixel_values - encoding["query_pixel_values"] = query_pixel_values - - if images is not None: - image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs) - - if text is not None and images is not None: - encoding["pixel_values"] = image_features.pixel_values - return encoding - elif query_images is not None and images is not None: - encoding["pixel_values"] = image_features.pixel_values - return encoding - elif text is not None or query_images is not None: - return encoding - else: - return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors) - - def post_process(self, *args, **kwargs): - """ - This method forwards all its arguments to [`OwlViTImageProcessor.post_process`]. Please refer to the docstring - of this method for more information. - """ - return self.image_processor.post_process(*args, **kwargs) - - def post_process_object_detection(self, *args, **kwargs): - """ - This method forwards all its arguments to [`OwlViTImageProcessor.post_process_object_detection`]. Please refer - to the docstring of this method for more information. - """ - return self.image_processor.post_process_object_detection(*args, **kwargs) - - def post_process_image_guided_detection(self, *args, **kwargs): - """ - This method forwards all its arguments to [`OwlViTImageProcessor.post_process_one_shot_object_detection`]. - Please refer to the docstring of this method for more information. - """ - return self.image_processor.post_process_image_guided_detection(*args, **kwargs) - - def batch_decode(self, *args, **kwargs): - """ - This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please - refer to the docstring of this method for more information. - """ - return self.tokenizer.batch_decode(*args, **kwargs) - - def decode(self, *args, **kwargs): - """ - This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to - the docstring of this method for more information. - """ - return self.tokenizer.decode(*args, **kwargs) - - @property - def feature_extractor_class(self): - warnings.warn( - "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.", - FutureWarning, - ) - return self.image_processor_class - - @property - def feature_extractor(self): - warnings.warn( - "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.", - FutureWarning, - ) - return self.image_processor diff --git a/spaces/yl12053/so-vits-4.1-Grass-Wonder/vencoder/whisper/utils.py b/spaces/yl12053/so-vits-4.1-Grass-Wonder/vencoder/whisper/utils.py deleted file mode 100644 index 5dacc173c40bcd6e999d728862e29a968000b12e..0000000000000000000000000000000000000000 --- a/spaces/yl12053/so-vits-4.1-Grass-Wonder/vencoder/whisper/utils.py +++ /dev/null @@ -1,163 +0,0 @@ -import json -import os -import sys -import zlib -from typing import Callable, TextIO - -system_encoding = sys.getdefaultencoding() - -if system_encoding != "utf-8": - def make_safe(string): - # replaces any character not representable using the system default encoding with an '?', - # avoiding UnicodeEncodeError (https://github.com/openai/whisper/discussions/729). - return string.encode(system_encoding, errors="replace").decode(system_encoding) -else: - def make_safe(string): - # utf-8 can encode any Unicode code point, so no need to do the round-trip encoding - return string - - -def exact_div(x, y): - assert x % y == 0 - return x // y - - -def str2bool(string): - str2val = {"True": True, "False": False} - if string in str2val: - return str2val[string] - else: - raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}") - - -def optional_int(string): - return None if string == "None" else int(string) - - -def optional_float(string): - return None if string == "None" else float(string) - - -def compression_ratio(text) -> float: - text_bytes = text.encode("utf-8") - return len(text_bytes) / len(zlib.compress(text_bytes)) - - -def format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = '.'): - assert seconds >= 0, "non-negative timestamp expected" - milliseconds = round(seconds * 1000.0) - - hours = milliseconds // 3_600_000 - milliseconds -= hours * 3_600_000 - - minutes = milliseconds // 60_000 - milliseconds -= minutes * 60_000 - - seconds = milliseconds // 1_000 - milliseconds -= seconds * 1_000 - - hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else "" - return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}" - - -class ResultWriter: - extension: str - - def __init__(self, output_dir: str): - self.output_dir = output_dir - - def __call__(self, result: dict, audio_path: str): - audio_basename = os.path.basename(audio_path) - output_path = os.path.join(self.output_dir, audio_basename + "." + self.extension) - - with open(output_path, "w", encoding="utf-8") as f: - self.write_result(result, file=f) - - def write_result(self, result: dict, file: TextIO): - raise NotImplementedError - - -class WriteTXT(ResultWriter): - extension: str = "txt" - - def write_result(self, result: dict, file: TextIO): - for segment in result["segments"]: - print(segment['text'].strip(), file=file, flush=True) - - -class WriteVTT(ResultWriter): - extension: str = "vtt" - - def write_result(self, result: dict, file: TextIO): - print("WEBVTT\n", file=file) - for segment in result["segments"]: - print( - f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n" - f"{segment['text'].strip().replace('-->', '->')}\n", - file=file, - flush=True, - ) - - -class WriteSRT(ResultWriter): - extension: str = "srt" - - def write_result(self, result: dict, file: TextIO): - for i, segment in enumerate(result["segments"], start=1): - # write srt lines - print( - f"{i}\n" - f"{format_timestamp(segment['start'], always_include_hours=True, decimal_marker=',')} --> " - f"{format_timestamp(segment['end'], always_include_hours=True, decimal_marker=',')}\n" - f"{segment['text'].strip().replace('-->', '->')}\n", - file=file, - flush=True, - ) - - -class WriteTSV(ResultWriter): - """ - Write a transcript to a file in TSV (tab-separated values) format containing lines like: - \t\t - - Using integer milliseconds as start and end times means there's no chance of interference from - an environment setting a language encoding that causes the decimal in a floating point number - to appear as a comma; also is faster and more efficient to parse & store, e.g., in C++. - """ - extension: str = "tsv" - - def write_result(self, result: dict, file: TextIO): - print("start", "end", "text", sep="\t", file=file) - for segment in result["segments"]: - print(round(1000 * segment['start']), file=file, end="\t") - print(round(1000 * segment['end']), file=file, end="\t") - print(segment['text'].strip().replace("\t", " "), file=file, flush=True) - - -class WriteJSON(ResultWriter): - extension: str = "json" - - def write_result(self, result: dict, file: TextIO): - json.dump(result, file) - - -def get_writer(output_format: str, output_dir: str) -> Callable[[dict, TextIO], None]: - writers = { - "txt": WriteTXT, - "vtt": WriteVTT, - "srt": WriteSRT, - "tsv": WriteTSV, - "json": WriteJSON, - } - - if output_format == "all": - all_writers = [writer(output_dir) for writer in writers.values()] - - def write_all(result: dict, file: TextIO): - for writer in all_writers: - writer(result, file) - - return write_all - - return writers[output_format](output_dir) - diff --git a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/tools/visualize_data.py b/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/tools/visualize_data.py deleted file mode 100644 index fd0ba8347bfd34fc8fac5ffef9aee10915ad1820..0000000000000000000000000000000000000000 --- a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/tools/visualize_data.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) Facebook, Inc. and its affiliates. -import argparse -import os -from itertools import chain -import cv2 -import tqdm - -from detectron2.config import get_cfg -from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_train_loader -from detectron2.data import detection_utils as utils -from detectron2.data.build import filter_images_with_few_keypoints -from detectron2.utils.logger import setup_logger -from detectron2.utils.visualizer import Visualizer - - -def setup(args): - cfg = get_cfg() - if args.config_file: - cfg.merge_from_file(args.config_file) - cfg.merge_from_list(args.opts) - cfg.DATALOADER.NUM_WORKERS = 0 - cfg.freeze() - return cfg - - -def parse_args(in_args=None): - parser = argparse.ArgumentParser(description="Visualize ground-truth data") - parser.add_argument( - "--source", - choices=["annotation", "dataloader"], - required=True, - help="visualize the annotations or the data loader (with pre-processing)", - ) - parser.add_argument("--config-file", metavar="FILE", help="path to config file") - parser.add_argument("--output-dir", default="./", help="path to output directory") - parser.add_argument("--show", action="store_true", help="show output in a window") - parser.add_argument( - "opts", - help="Modify config options using the command-line", - default=None, - nargs=argparse.REMAINDER, - ) - return parser.parse_args(in_args) - - -if __name__ == "__main__": - args = parse_args() - logger = setup_logger() - logger.info("Arguments: " + str(args)) - cfg = setup(args) - - dirname = args.output_dir - os.makedirs(dirname, exist_ok=True) - metadata = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]) - - def output(vis, fname): - if args.show: - print(fname) - cv2.imshow("window", vis.get_image()[:, :, ::-1]) - cv2.waitKey() - else: - filepath = os.path.join(dirname, fname) - print("Saving to {} ...".format(filepath)) - vis.save(filepath) - - scale = 1.0 - if args.source == "dataloader": - train_data_loader = build_detection_train_loader(cfg) - for batch in train_data_loader: - for per_image in batch: - # Pytorch tensor is in (C, H, W) format - img = per_image["image"].permute(1, 2, 0).cpu().detach().numpy() - img = utils.convert_image_to_rgb(img, cfg.INPUT.FORMAT) - - visualizer = Visualizer(img, metadata=metadata, scale=scale) - target_fields = per_image["instances"].get_fields() - labels = [metadata.thing_classes[i] for i in target_fields["gt_classes"]] - vis = visualizer.overlay_instances( - labels=labels, - boxes=target_fields.get("gt_boxes", None), - masks=target_fields.get("gt_masks", None), - keypoints=target_fields.get("gt_keypoints", None), - ) - output(vis, str(per_image["image_id"]) + ".jpg") - else: - dicts = list(chain.from_iterable([DatasetCatalog.get(k) for k in cfg.DATASETS.TRAIN])) - if cfg.MODEL.KEYPOINT_ON: - dicts = filter_images_with_few_keypoints(dicts, 1) - for dic in tqdm.tqdm(dicts): - img = utils.read_image(dic["file_name"], "RGB") - visualizer = Visualizer(img, metadata=metadata, scale=scale) - vis = visualizer.draw_dataset_dict(dic) - output(vis, os.path.basename(dic["file_name"])) diff --git a/spaces/younker/chatgpt-turbo/client/node_modules/autoprefixer/lib/hacks/fullscreen.js b/spaces/younker/chatgpt-turbo/client/node_modules/autoprefixer/lib/hacks/fullscreen.js deleted file mode 100644 index 5a7439045420af2dc952f4c77ccee976467c7e25..0000000000000000000000000000000000000000 --- a/spaces/younker/chatgpt-turbo/client/node_modules/autoprefixer/lib/hacks/fullscreen.js +++ /dev/null @@ -1,20 +0,0 @@ -let Selector = require('../selector') - -class Fullscreen extends Selector { - /** - * Return different selectors depend on prefix - */ - prefixed(prefix) { - if (prefix === '-webkit-') { - return ':-webkit-full-screen' - } - if (prefix === '-moz-') { - return ':-moz-full-screen' - } - return `:${prefix}fullscreen` - } -} - -Fullscreen.names = [':fullscreen'] - -module.exports = Fullscreen diff --git a/spaces/ysharma/LLaVA_v1/llava/model/language_model/llava_llama.py b/spaces/ysharma/LLaVA_v1/llava/model/language_model/llava_llama.py deleted file mode 100644 index d9ce3e86f788856e669a597b15939142138fd230..0000000000000000000000000000000000000000 --- a/spaces/ysharma/LLaVA_v1/llava/model/language_model/llava_llama.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright 2023 Haotian Liu -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import List, Optional, Tuple, Union - -import torch -import torch.nn as nn -from torch.nn import CrossEntropyLoss - -from transformers import AutoConfig, AutoModelForCausalLM, \ - LlamaConfig, LlamaModel, LlamaForCausalLM - -from transformers.modeling_outputs import CausalLMOutputWithPast - -from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM - - -class LlavaConfig(LlamaConfig): - model_type = "llava" - - -class LlavaLlamaModel(LlavaMetaModel, LlamaModel): - config_class = LlavaConfig - - def __init__(self, config: LlamaConfig): - super(LlavaLlamaModel, self).__init__(config) - - -class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM): - config_class = LlavaConfig - - def __init__(self, config): - super(LlamaForCausalLM, self).__init__(config) - self.model = LlavaLlamaModel(config) - - self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) - - # Initialize weights and apply final processing - self.post_init() - - def get_model(self): - return self.model - - def forward( - self, - input_ids: torch.LongTensor = None, - attention_mask: Optional[torch.Tensor] = None, - past_key_values: Optional[List[torch.FloatTensor]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - labels: Optional[torch.LongTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - images: Optional[torch.FloatTensor] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, CausalLMOutputWithPast]: - 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 - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) - - # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) - outputs = self.model( - input_ids=input_ids, - attention_mask=attention_mask, - past_key_values=past_key_values, - inputs_embeds=inputs_embeds, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict - ) - - hidden_states = outputs[0] - logits = self.lm_head(hidden_states) - - loss = None - if labels is not None: - # Shift so that tokens < n predict n - shift_logits = logits[..., :-1, :].contiguous() - shift_labels = labels[..., 1:].contiguous() - # Flatten the tokens - loss_fct = CrossEntropyLoss() - shift_logits = shift_logits.view(-1, self.config.vocab_size) - shift_labels = shift_labels.view(-1) - # Enable model/pipeline parallelism - shift_labels = shift_labels.to(shift_logits.device) - loss = loss_fct(shift_logits, shift_labels) - - if not return_dict: - output = (logits,) + outputs[1:] - return (loss,) + output if loss is not None else output - - return CausalLMOutputWithPast( - loss=loss, - logits=logits, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - - def prepare_inputs_for_generation( - self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs - ): - if past_key_values: - input_ids = input_ids[:, -1:] - - # if `inputs_embeds` are passed, we only want to use them in the 1st generation step - if inputs_embeds is not None and past_key_values is None: - model_inputs = {"inputs_embeds": inputs_embeds} - else: - model_inputs = {"input_ids": input_ids} - - model_inputs.update( - { - "past_key_values": past_key_values, - "use_cache": kwargs.get("use_cache"), - "attention_mask": attention_mask, - "images": kwargs.get("images", None), - } - ) - return model_inputs - -AutoConfig.register("llava", LlavaConfig) -AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM) diff --git a/spaces/yuan1615/EmpathyVC/data_utils.py b/spaces/yuan1615/EmpathyVC/data_utils.py deleted file mode 100644 index b102d5a380218da013ed07a3cb878923b646cca7..0000000000000000000000000000000000000000 --- a/spaces/yuan1615/EmpathyVC/data_utils.py +++ /dev/null @@ -1,423 +0,0 @@ -import time -import os -import random -import numpy as np -import torch -import torch.utils.data - -import commons -from mel_processing import spectrogram_torch -from utils import load_wav_to_torch, load_filepaths_and_text -from text import text_to_sequence, cleaned_text_to_sequence, prosody_to_sequence - - -class TextAudioLoader(torch.utils.data.Dataset): - """ - 1) loads audio, text pairs - 2) normalizes text and converts them to sequences of integers - 3) computes spectrograms from audio files. - """ - def __init__(self, audiopaths_and_text, hparams): - self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) - self.text_cleaners = hparams.text_cleaners - self.max_wav_value = hparams.max_wav_value - self.sampling_rate = hparams.sampling_rate - self.filter_length = hparams.filter_length - self.hop_length = hparams.hop_length - self.win_length = hparams.win_length - self.sampling_rate = hparams.sampling_rate - - self.cleaned_text = getattr(hparams, "cleaned_text", False) - - self.add_blank = hparams.add_blank - self.min_text_len = getattr(hparams, "min_text_len", 1) - self.max_text_len = getattr(hparams, "max_text_len", 190) - - random.seed(1234) - random.shuffle(self.audiopaths_and_text) - self._filter() - - - def _filter(self): - """ - Filter text & store spec lengths - """ - # Store spectrogram lengths for Bucketing - # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2) - # spec_length = wav_length // hop_length - - audiopaths_and_text_new = [] - lengths = [] - for audiopath, text, prosody in self.audiopaths_and_text: - if self.min_text_len <= len(text) and len(text) <= self.max_text_len: - audiopaths_and_text_new.append([audiopath, text, prosody]) - lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length)) - self.audiopaths_and_text = audiopaths_and_text_new - self.lengths = lengths - - def get_audio_text_pair(self, audiopath_and_text): - # separate filename and text - audiopath, text, prosody = audiopath_and_text[0], audiopath_and_text[1], audiopath_and_text[2] - text = self.get_text(text) - prosody = self.get_prosody(prosody) - spec, wav = self.get_audio(audiopath) - return (text, prosody, spec, wav) - - def get_audio(self, filename): - audio, sampling_rate = load_wav_to_torch(filename) - if sampling_rate != self.sampling_rate: - raise ValueError("{} {} SR doesn't match target {} SR".format( - sampling_rate, self.sampling_rate)) - audio_norm = audio / self.max_wav_value - audio_norm = audio_norm.unsqueeze(0) - spec_filename = filename.replace(".wav", ".spec.pt") - if os.path.exists(spec_filename): - spec = torch.load(spec_filename) - else: - spec = spectrogram_torch(audio_norm, self.filter_length, - self.sampling_rate, self.hop_length, self.win_length, - center=False) - spec = torch.squeeze(spec, 0) - torch.save(spec, spec_filename) - return spec, audio_norm - - def get_text(self, text): - if self.cleaned_text: - text_norm = cleaned_text_to_sequence(text) - else: - text_norm = text_to_sequence(text, self.text_cleaners) - if self.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def get_prosody(self, prosody): - text_norm = prosody_to_sequence(prosody) - if self.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def __getitem__(self, index): - return self.get_audio_text_pair(self.audiopaths_and_text[index]) - - def __len__(self): - return len(self.audiopaths_and_text) - - -class TextAudioCollate(): - """ Zero-pads model inputs and targets - """ - def __init__(self, return_ids=False): - self.return_ids = return_ids - - def __call__(self, batch): - """Collate's training batch from normalized text and aduio - PARAMS - ------ - batch: [text_normalized, spec_normalized, wav_normalized] - new:: (text, prosody, spec, wav) - """ - # Right zero-pad all one-hot text sequences to max input length - _, ids_sorted_decreasing = torch.sort( - torch.LongTensor([x[2].size(1) for x in batch]), - dim=0, descending=True) - - max_text_len = max([len(x[0]) for x in batch]) - max_prosody_len = max([len(x[1]) for x in batch]) - max_spec_len = max([x[2].size(1) for x in batch]) - max_wav_len = max([x[3].size(1) for x in batch]) - - text_lengths = torch.LongTensor(len(batch)) - prosody_lengths = torch.LongTensor(len(batch)) - spec_lengths = torch.LongTensor(len(batch)) - wav_lengths = torch.LongTensor(len(batch)) - - text_padded = torch.LongTensor(len(batch), max_text_len) - prosody_padded = torch.LongTensor(len(batch), max_prosody_len) - spec_padded = torch.FloatTensor(len(batch), batch[0][2].size(0), max_spec_len) - wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) - text_padded.zero_() - prosody_padded.zero_() - spec_padded.zero_() - wav_padded.zero_() - for i in range(len(ids_sorted_decreasing)): - row = batch[ids_sorted_decreasing[i]] - - text = row[0] - text_padded[i, :text.size(0)] = text - text_lengths[i] = text.size(0) - - prosody = row[1] - prosody_padded[i, :prosody.size(0)] = prosody - - spec = row[2] - spec_padded[i, :, :spec.size(1)] = spec - spec_lengths[i] = spec.size(1) - - wav = row[3] - wav_padded[i, :, :wav.size(1)] = wav - wav_lengths[i] = wav.size(1) - - if self.return_ids: - return text_padded, text_lengths, prosody_padded, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing - return text_padded, text_lengths, prosody_padded, spec_padded, spec_lengths, wav_padded, wav_lengths - - -"""Multi speaker version""" -class TextAudioSpeakerLoader(torch.utils.data.Dataset): - """ - 1) loads audio, speaker_id, text pairs - 2) normalizes text and converts them to sequences of integers - 3) computes spectrograms from audio files. - """ - def __init__(self, audiopaths_sid_text, hparams): - self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text) - self.text_cleaners = hparams.text_cleaners - self.max_wav_value = hparams.max_wav_value - self.sampling_rate = hparams.sampling_rate - self.filter_length = hparams.filter_length - self.hop_length = hparams.hop_length - self.win_length = hparams.win_length - self.sampling_rate = hparams.sampling_rate - - self.cleaned_text = getattr(hparams, "cleaned_text", False) - - self.add_blank = hparams.add_blank - self.min_text_len = getattr(hparams, "min_text_len", 1) - self.max_text_len = getattr(hparams, "max_text_len", 190) - - random.seed(1234) - random.shuffle(self.audiopaths_sid_text) - self._filter() - - def _filter(self): - """ - Filter text & store spec lengths - """ - # Store spectrogram lengths for Bucketing - # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2) - # spec_length = wav_length // hop_length - - audiopaths_sid_text_new = [] - lengths = [] - for audiopath, sid, text, prosody in self.audiopaths_sid_text: - if self.min_text_len <= len(text) and len(text) <= self.max_text_len: - audiopaths_sid_text_new.append([audiopath, sid, text, prosody]) - lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length)) - self.audiopaths_sid_text = audiopaths_sid_text_new - self.lengths = lengths - - def get_audio_text_speaker_pair(self, audiopath_sid_text): - # separate filename, speaker_id and text - audiopath, sid, text, prosody = audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2], audiopath_sid_text[3] - text = self.get_text(text) - spec, wav = self.get_audio(audiopath) - sid = self.get_sid(sid) - prosody = self.get_prosody(prosody) - return (text, prosody, spec, wav, sid) - - def get_audio(self, filename): - audio, sampling_rate = load_wav_to_torch(filename) - if sampling_rate != self.sampling_rate: - raise ValueError("{} {} SR doesn't match target {} SR".format( - sampling_rate, self.sampling_rate)) - audio_norm = audio / self.max_wav_value - audio_norm = audio_norm.unsqueeze(0) - spec_filename = filename.replace(".wav", ".spec.pt") - if os.path.exists(spec_filename): - spec = torch.load(spec_filename) - else: - spec = spectrogram_torch(audio_norm, self.filter_length, - self.sampling_rate, self.hop_length, self.win_length, - center=False) - spec = torch.squeeze(spec, 0) - torch.save(spec, spec_filename) - return spec, audio_norm - - def get_text(self, text): - if self.cleaned_text: - text_norm = cleaned_text_to_sequence(text) - else: - text_norm = text_to_sequence(text, self.text_cleaners) - if self.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def get_prosody(self, prosody): - text_norm = prosody_to_sequence(prosody) - if self.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def get_sid(self, sid): - sid = torch.LongTensor([int(sid)]) - return sid - - def __getitem__(self, index): - return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index]) - - def __len__(self): - return len(self.audiopaths_sid_text) - - -class TextAudioSpeakerCollate(): - """ Zero-pads model inputs and targets - """ - def __init__(self, return_ids=False): - self.return_ids = return_ids - - def __call__(self, batch): - """Collate's training batch from normalized text, audio and speaker identities - PARAMS - ------ - batch: [text_normalized, spec_normalized, wav_normalized, sid] - """ - # Right zero-pad all one-hot text sequences to max input length - _, ids_sorted_decreasing = torch.sort( - torch.LongTensor([x[2].size(1) for x in batch]), - dim=0, descending=True) - - max_text_len = max([len(x[0]) for x in batch]) - max_prosody_len = max([len(x[1]) for x in batch]) - max_spec_len = max([x[2].size(1) for x in batch]) - max_wav_len = max([x[3].size(1) for x in batch]) - - text_lengths = torch.LongTensor(len(batch)) - prosody_lengths = torch.LongTensor(len(batch)) - spec_lengths = torch.LongTensor(len(batch)) - wav_lengths = torch.LongTensor(len(batch)) - sid = torch.LongTensor(len(batch)) - - text_padded = torch.LongTensor(len(batch), max_text_len) - prosody_padded = torch.LongTensor(len(batch), max_prosody_len) - spec_padded = torch.FloatTensor(len(batch), batch[0][2].size(0), max_spec_len) - wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) - text_padded.zero_() - prosody_padded.zero_() - spec_padded.zero_() - wav_padded.zero_() - for i in range(len(ids_sorted_decreasing)): - row = batch[ids_sorted_decreasing[i]] - - text = row[0] - text_padded[i, :text.size(0)] = text - text_lengths[i] = text.size(0) - - prosody = row[1] - prosody_padded[i, :prosody.size(0)] = prosody - - spec = row[2] - spec_padded[i, :, :spec.size(1)] = spec - spec_lengths[i] = spec.size(1) - - wav = row[3] - wav_padded[i, :, :wav.size(1)] = wav - wav_lengths[i] = wav.size(1) - - sid[i] = row[4] - - if self.return_ids: - return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing - return text_padded, text_lengths, prosody_padded, spec_padded, spec_lengths, wav_padded, wav_lengths, sid - - -class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler): - """ - Maintain similar input lengths in a batch. - Length groups are specified by boundaries. - Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}. - - It removes samples which are not included in the boundaries. - Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded. - """ - def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True): - super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle) - self.lengths = dataset.lengths - self.batch_size = batch_size - self.boundaries = boundaries - - self.buckets, self.num_samples_per_bucket = self._create_buckets() - self.total_size = sum(self.num_samples_per_bucket) - self.num_samples = self.total_size // self.num_replicas - - def _create_buckets(self): - buckets = [[] for _ in range(len(self.boundaries) - 1)] - for i in range(len(self.lengths)): - length = self.lengths[i] - idx_bucket = self._bisect(length) - if idx_bucket != -1: - buckets[idx_bucket].append(i) - - for i in range(len(buckets) - 1, 0, -1): - if len(buckets[i]) == 0: - buckets.pop(i) - self.boundaries.pop(i+1) - - num_samples_per_bucket = [] - for i in range(len(buckets)): - len_bucket = len(buckets[i]) - total_batch_size = self.num_replicas * self.batch_size - rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size - num_samples_per_bucket.append(len_bucket + rem) - return buckets, num_samples_per_bucket - - def __iter__(self): - # deterministically shuffle based on epoch - g = torch.Generator() - g.manual_seed(self.epoch) - - indices = [] - if self.shuffle: - for bucket in self.buckets: - indices.append(torch.randperm(len(bucket), generator=g).tolist()) - else: - for bucket in self.buckets: - indices.append(list(range(len(bucket)))) - - batches = [] - for i in range(len(self.buckets)): - bucket = self.buckets[i] - len_bucket = len(bucket) - ids_bucket = indices[i] - num_samples_bucket = self.num_samples_per_bucket[i] - - # add extra samples to make it evenly divisible - rem = num_samples_bucket - len_bucket - ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)] - - # subsample - ids_bucket = ids_bucket[self.rank::self.num_replicas] - - # batching - for j in range(len(ids_bucket) // self.batch_size): - batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]] - batches.append(batch) - - if self.shuffle: - batch_ids = torch.randperm(len(batches), generator=g).tolist() - batches = [batches[i] for i in batch_ids] - self.batches = batches - - assert len(self.batches) * self.batch_size == self.num_samples - return iter(self.batches) - - def _bisect(self, x, lo=0, hi=None): - if hi is None: - hi = len(self.boundaries) - 1 - - if hi > lo: - mid = (hi + lo) // 2 - if self.boundaries[mid] < x and x <= self.boundaries[mid+1]: - return mid - elif x <= self.boundaries[mid]: - return self._bisect(x, lo, mid) - else: - return self._bisect(x, mid + 1, hi) - else: - return -1 - - def __len__(self): - return self.num_samples // self.batch_size diff --git a/spaces/yufiofficial/MusicGenQ/audiocraft/models/builders.py b/spaces/yufiofficial/MusicGenQ/audiocraft/models/builders.py deleted file mode 100644 index 77ee5f96fea2e3c9e475fe961bc1a5ee473ed8eb..0000000000000000000000000000000000000000 --- a/spaces/yufiofficial/MusicGenQ/audiocraft/models/builders.py +++ /dev/null @@ -1,218 +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. - -""" -All the functions to build the relevant models and modules -from the Hydra config. -""" - -import typing as tp -import warnings - -import audiocraft -import omegaconf -import torch - -from .encodec import CompressionModel, EncodecModel, FlattenedCompressionModel # noqa -from .lm import LMModel -from ..modules.codebooks_patterns import ( - CodebooksPatternProvider, - DelayedPatternProvider, - ParallelPatternProvider, - UnrolledPatternProvider, - VALLEPattern, - MusicLMPattern, -) -from ..modules.conditioners import ( - BaseConditioner, - ConditioningProvider, - LUTConditioner, - T5Conditioner, - ConditionFuser, - ChromaStemConditioner, -) -from .. import quantization as qt -from ..utils.utils import dict_from_config - - -def get_quantizer(quantizer: str, cfg: omegaconf.DictConfig, dimension: int) -> qt.BaseQuantizer: - klass = { - 'no_quant': qt.DummyQuantizer, - 'rvq': qt.ResidualVectorQuantizer - }[quantizer] - kwargs = dict_from_config(getattr(cfg, quantizer)) - if quantizer != 'no_quant': - kwargs['dimension'] = dimension - return klass(**kwargs) - - -def get_encodec_autoencoder(encoder_name: str, cfg: omegaconf.DictConfig): - if encoder_name == 'seanet': - kwargs = dict_from_config(getattr(cfg, 'seanet')) - encoder_override_kwargs = kwargs.pop('encoder') - decoder_override_kwargs = kwargs.pop('decoder') - encoder_kwargs = {**kwargs, **encoder_override_kwargs} - decoder_kwargs = {**kwargs, **decoder_override_kwargs} - encoder = audiocraft.modules.SEANetEncoder(**encoder_kwargs) - decoder = audiocraft.modules.SEANetDecoder(**decoder_kwargs) - return encoder, decoder - else: - raise KeyError(f'Unexpected compression model {cfg.compression_model}') - - -def get_compression_model(cfg: omegaconf.DictConfig) -> CompressionModel: - """Instantiate a compression model. - """ - if cfg.compression_model == 'encodec': - kwargs = dict_from_config(getattr(cfg, 'encodec')) - encoder_name = kwargs.pop('autoencoder') - quantizer_name = kwargs.pop('quantizer') - encoder, decoder = get_encodec_autoencoder(encoder_name, cfg) - quantizer = get_quantizer(quantizer_name, cfg, encoder.dimension) - frame_rate = kwargs['sample_rate'] // encoder.hop_length - renormalize = kwargs.pop('renormalize', None) - renorm = kwargs.pop('renorm') - if renormalize is None: - renormalize = renorm is not None - warnings.warn("You are using a deprecated EnCodec model. Please migrate to new renormalization.") - return EncodecModel(encoder, decoder, quantizer, - frame_rate=frame_rate, renormalize=renormalize, **kwargs).to(cfg.device) - else: - raise KeyError(f'Unexpected compression model {cfg.compression_model}') - - -def get_lm_model(cfg: omegaconf.DictConfig) -> LMModel: - """Instantiate a transformer LM. - """ - if cfg.lm_model == 'transformer_lm': - kwargs = dict_from_config(getattr(cfg, 'transformer_lm')) - n_q = kwargs['n_q'] - q_modeling = kwargs.pop('q_modeling', None) - codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern') - attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout')) - cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance')) - cfg_prob, cfg_coef = cls_free_guidance["training_dropout"], cls_free_guidance["inference_coef"] - fuser = get_condition_fuser(cfg) - condition_provider = get_conditioner_provider(kwargs["dim"], cfg).to(cfg.device) - if len(fuser.fuse2cond['cross']) > 0: # enforce cross-att programatically - kwargs['cross_attention'] = True - if codebooks_pattern_cfg.modeling is None: - assert q_modeling is not None, \ - 'LM model should either have a codebook pattern defined or transformer_lm.q_modeling' - codebooks_pattern_cfg = omegaconf.OmegaConf.create( - {'modeling': q_modeling, 'delay': {'delays': list(range(n_q))}} - ) - pattern_provider = get_codebooks_pattern_provider(n_q, codebooks_pattern_cfg) - return LMModel( - pattern_provider=pattern_provider, - condition_provider=condition_provider, - fuser=fuser, - cfg_dropout=cfg_prob, - cfg_coef=cfg_coef, - attribute_dropout=attribute_dropout, - dtype=getattr(torch, cfg.dtype), - device=cfg.device, - **kwargs - ).to(cfg.device) - else: - raise KeyError(f'Unexpected LM model {cfg.lm_model}') - - -def get_conditioner_provider(output_dim: int, cfg: omegaconf.DictConfig) -> ConditioningProvider: - """Instantiate a conditioning model. - """ - device = cfg.device - duration = cfg.dataset.segment_duration - cfg = getattr(cfg, "conditioners") - cfg = omegaconf.OmegaConf.create({}) if cfg is None else cfg - conditioners: tp.Dict[str, BaseConditioner] = {} - with omegaconf.open_dict(cfg): - condition_provider_args = cfg.pop('args', {}) - for cond, cond_cfg in cfg.items(): - model_type = cond_cfg["model"] - model_args = cond_cfg[model_type] - if model_type == "t5": - conditioners[str(cond)] = T5Conditioner(output_dim=output_dim, device=device, **model_args) - elif model_type == "lut": - conditioners[str(cond)] = LUTConditioner(output_dim=output_dim, **model_args) - elif model_type == "chroma_stem": - model_args.pop('cache_path', None) - conditioners[str(cond)] = ChromaStemConditioner( - output_dim=output_dim, - duration=duration, - device=device, - **model_args - ) - else: - raise ValueError(f"unrecognized conditioning model: {model_type}") - conditioner = ConditioningProvider(conditioners, device=device, **condition_provider_args) - return conditioner - - -def get_condition_fuser(cfg: omegaconf.DictConfig) -> ConditionFuser: - """Instantiate a condition fuser object. - """ - fuser_cfg = getattr(cfg, "fuser") - fuser_methods = ["sum", "cross", "prepend", "input_interpolate"] - fuse2cond = {k: fuser_cfg[k] for k in fuser_methods} - kwargs = {k: v for k, v in fuser_cfg.items() if k not in fuser_methods} - fuser = ConditionFuser(fuse2cond=fuse2cond, **kwargs) - return fuser - - -def get_codebooks_pattern_provider(n_q: int, cfg: omegaconf.DictConfig) -> CodebooksPatternProvider: - """Instantiate a codebooks pattern provider object. - """ - pattern_providers = { - 'parallel': ParallelPatternProvider, - 'delay': DelayedPatternProvider, - 'unroll': UnrolledPatternProvider, - 'valle': VALLEPattern, - 'musiclm': MusicLMPattern, - } - name = cfg.modeling - kwargs = dict_from_config(cfg.get(name)) if hasattr(cfg, name) else {} - klass = pattern_providers[name] - return klass(n_q, **kwargs) - - -def get_debug_compression_model(device='cpu'): - """Instantiate a debug compression model to be used for unit tests. - """ - seanet_kwargs = { - 'n_filters': 4, - 'n_residual_layers': 1, - 'dimension': 32, - 'ratios': [10, 8, 16] # 25 Hz at 32kHz - } - encoder = audiocraft.modules.SEANetEncoder(**seanet_kwargs) - decoder = audiocraft.modules.SEANetDecoder(**seanet_kwargs) - quantizer = qt.ResidualVectorQuantizer(dimension=32, bins=400, n_q=4) - init_x = torch.randn(8, 32, 128) - quantizer(init_x, 1) # initialize kmeans etc. - compression_model = EncodecModel( - encoder, decoder, quantizer, - frame_rate=25, sample_rate=32000, channels=1).to(device) - return compression_model.eval() - - -def get_debug_lm_model(device='cpu'): - """Instantiate a debug LM to be used for unit tests. - """ - pattern = DelayedPatternProvider(n_q=4) - dim = 16 - providers = { - 'description': LUTConditioner(n_bins=128, dim=dim, output_dim=dim, tokenizer="whitespace"), - } - condition_provider = ConditioningProvider(providers) - fuser = ConditionFuser( - {'cross': ['description'], 'prepend': [], - 'sum': [], 'input_interpolate': []}) - lm = LMModel( - pattern, condition_provider, fuser, - n_q=4, card=400, dim=dim, num_heads=4, custom=True, num_layers=2, - cross_attention=True, causal=True) - return lm.to(device).eval() diff --git a/spaces/zhang-wei-jian/docker/node_modules/cache-content-type/README.md b/spaces/zhang-wei-jian/docker/node_modules/cache-content-type/README.md deleted file mode 100644 index 605d6c44631b10948e29e0fdaaf7ee8389a2f54f..0000000000000000000000000000000000000000 --- a/spaces/zhang-wei-jian/docker/node_modules/cache-content-type/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## cache-content-type - -The same as [mime-types](https://github.com/jshttp/mime-types)'s contentType method, but with result cached. - -### Install - -```bash -npm i cache-content-type -``` - -### Usage - -```js -const getType = require('cache-content-type'); -const contentType = getType('html'); -assert(contentType === 'text/html; charset=utf-8'); -``` diff --git a/spaces/zhenwusw/JoJoGAN/e4e/options/train_options.py b/spaces/zhenwusw/JoJoGAN/e4e/options/train_options.py deleted file mode 100644 index 583ea1423fdc9a649cd7044d74d554bf0ac2bf51..0000000000000000000000000000000000000000 --- a/spaces/zhenwusw/JoJoGAN/e4e/options/train_options.py +++ /dev/null @@ -1,84 +0,0 @@ -from argparse import ArgumentParser -from configs.paths_config import model_paths - - -class TrainOptions: - - def __init__(self): - self.parser = ArgumentParser() - self.initialize() - - def initialize(self): - self.parser.add_argument('--exp_dir', type=str, help='Path to experiment output directory') - self.parser.add_argument('--dataset_type', default='ffhq_encode', type=str, - help='Type of dataset/experiment to run') - self.parser.add_argument('--encoder_type', default='Encoder4Editing', type=str, help='Which encoder to use') - - self.parser.add_argument('--batch_size', default=4, type=int, help='Batch size for training') - self.parser.add_argument('--test_batch_size', default=2, type=int, help='Batch size for testing and inference') - self.parser.add_argument('--workers', default=4, type=int, help='Number of train dataloader workers') - self.parser.add_argument('--test_workers', default=2, type=int, - help='Number of test/inference dataloader workers') - - self.parser.add_argument('--learning_rate', default=0.0001, type=float, help='Optimizer learning rate') - self.parser.add_argument('--optim_name', default='ranger', type=str, help='Which optimizer to use') - self.parser.add_argument('--train_decoder', default=False, type=bool, help='Whether to train the decoder model') - self.parser.add_argument('--start_from_latent_avg', action='store_true', - help='Whether to add average latent vector to generate codes from encoder.') - self.parser.add_argument('--lpips_type', default='alex', type=str, help='LPIPS backbone') - - self.parser.add_argument('--lpips_lambda', default=0.8, type=float, help='LPIPS loss multiplier factor') - self.parser.add_argument('--id_lambda', default=0.1, type=float, help='ID loss multiplier factor') - self.parser.add_argument('--l2_lambda', default=1.0, type=float, help='L2 loss multiplier factor') - - self.parser.add_argument('--stylegan_weights', default=model_paths['stylegan_ffhq'], type=str, - help='Path to StyleGAN model weights') - self.parser.add_argument('--stylegan_size', default=1024, type=int, - help='size of pretrained StyleGAN Generator') - self.parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to pSp model checkpoint') - - self.parser.add_argument('--max_steps', default=500000, type=int, help='Maximum number of training steps') - self.parser.add_argument('--image_interval', default=100, type=int, - help='Interval for logging train images during training') - self.parser.add_argument('--board_interval', default=50, type=int, - help='Interval for logging metrics to tensorboard') - self.parser.add_argument('--val_interval', default=1000, type=int, help='Validation interval') - self.parser.add_argument('--save_interval', default=None, type=int, help='Model checkpoint interval') - - # Discriminator flags - self.parser.add_argument('--w_discriminator_lambda', default=0, type=float, help='Dw loss multiplier') - self.parser.add_argument('--w_discriminator_lr', default=2e-5, type=float, help='Dw learning rate') - self.parser.add_argument("--r1", type=float, default=10, help="weight of the r1 regularization") - self.parser.add_argument("--d_reg_every", type=int, default=16, - help="interval for applying r1 regularization") - self.parser.add_argument('--use_w_pool', action='store_true', - help='Whether to store a latnet codes pool for the discriminator\'s training') - self.parser.add_argument("--w_pool_size", type=int, default=50, - help="W\'s pool size, depends on --use_w_pool") - - # e4e specific - self.parser.add_argument('--delta_norm', type=int, default=2, help="norm type of the deltas") - self.parser.add_argument('--delta_norm_lambda', type=float, default=2e-4, help="lambda for delta norm loss") - - # Progressive training - self.parser.add_argument('--progressive_steps', nargs='+', type=int, default=None, - help="The training steps of training new deltas. steps[i] starts the delta_i training") - self.parser.add_argument('--progressive_start', type=int, default=None, - help="The training step to start training the deltas, overrides progressive_steps") - self.parser.add_argument('--progressive_step_every', type=int, default=2_000, - help="Amount of training steps for each progressive step") - - # Save additional training info to enable future training continuation from produced checkpoints - self.parser.add_argument('--save_training_data', action='store_true', - help='Save intermediate training data to resume training from the checkpoint') - self.parser.add_argument('--sub_exp_dir', default=None, type=str, help='Name of sub experiment directory') - self.parser.add_argument('--keep_optimizer', action='store_true', - help='Whether to continue from the checkpoint\'s optimizer') - self.parser.add_argument('--resume_training_from_ckpt', default=None, type=str, - help='Path to training checkpoint, works when --save_training_data was set to True') - self.parser.add_argument('--update_param_list', nargs='+', type=str, default=None, - help="Name of training parameters to update the loaded training checkpoint") - - def parse(self): - opts = self.parser.parse_args() - return opts diff --git a/spaces/zhigangjiang/3D-Room-Layout-Estimation_LGT-Net/evaluation/iou.py b/spaces/zhigangjiang/3D-Room-Layout-Estimation_LGT-Net/evaluation/iou.py deleted file mode 100644 index 0e4004302f50b9a55561be617d80051b55e0ff44..0000000000000000000000000000000000000000 --- a/spaces/zhigangjiang/3D-Room-Layout-Estimation_LGT-Net/evaluation/iou.py +++ /dev/null @@ -1,148 +0,0 @@ -""" -@date: 2021/6/29 -@description: -The method with "_floorplan" suffix is only for comparison, which is used for calculation in LED2-net. -However, the floorplan is affected by show_radius. Setting too large will result in the decrease of accuracy, -and setting too small will result in the failure of calculation beyond the range. -""" -import numpy as np -from shapely.geometry import Polygon - - -def calc_inter_area(dt_xz, gt_xz): - """ - :param dt_xz: Prediction boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :param gt_xz: Ground truth boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :return: - """ - dt_polygon = Polygon(dt_xz) - gt_polygon = Polygon(gt_xz) - - dt_area = dt_polygon.area - gt_area = gt_polygon.area - inter_area = dt_polygon.intersection(gt_polygon).area - return dt_area, gt_area, inter_area - - -def calc_IoU_2D(dt_xz, gt_xz): - """ - :param dt_xz: Prediction boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :param gt_xz: Ground truth boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :return: - """ - dt_area, gt_area, inter_area = calc_inter_area(dt_xz, gt_xz) - iou_2d = inter_area / (gt_area + dt_area - inter_area) - return iou_2d - - -def calc_IoU_3D(dt_xz, gt_xz, dt_height, gt_height): - """ - :param dt_xz: Prediction boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :param gt_xz: Ground truth boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :param dt_height: - :param gt_height: - :return: - """ - dt_area, gt_area, inter_area = calc_inter_area(dt_xz, gt_xz) - dt_volume = dt_area * dt_height - gt_volume = gt_area * gt_height - inter_volume = inter_area * min(dt_height, gt_height) - iou_3d = inter_volume / (dt_volume + gt_volume - inter_volume) - return iou_3d - - -def calc_IoU(dt_xz, gt_xz, dt_height, gt_height): - """ - :param dt_xz: Prediction boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :param gt_xz: Ground truth boundaries can also be corners, format: [[x1, z1], [x2, z2], ...] - :param dt_height: - :param gt_height: - :return: - """ - dt_area, gt_area, inter_area = calc_inter_area(dt_xz, gt_xz) - iou_2d = inter_area / (gt_area + dt_area - inter_area) - - dt_volume = dt_area * dt_height - gt_volume = gt_area * gt_height - inter_volume = inter_area * min(dt_height, gt_height) - iou_3d = inter_volume / (dt_volume + gt_volume - inter_volume) - - return iou_2d, iou_3d - - -def calc_Iou_height(dt_height, gt_height): - return min(dt_height, gt_height) / max(dt_height, gt_height) - - -# the following is for testing only -def calc_inter_area_floorplan(dt_floorplan, gt_floorplan): - intersect = np.sum(np.logical_and(dt_floorplan, gt_floorplan)) - dt_area = np.sum(dt_floorplan) - gt_area = np.sum(gt_floorplan) - return dt_area, gt_area, intersect - - -def calc_IoU_2D_floorplan(dt_floorplan, gt_floorplan): - dt_area, gt_area, inter_area = calc_inter_area_floorplan(dt_floorplan, gt_floorplan) - iou_2d = inter_area / (gt_area + dt_area - inter_area) - return iou_2d - - -def calc_IoU_3D_floorplan(dt_floorplan, gt_floorplan, dt_height, gt_height): - dt_area, gt_area, inter_area = calc_inter_area_floorplan(dt_floorplan, gt_floorplan) - dt_volume = dt_area * dt_height - gt_volume = gt_area * gt_height - inter_volume = inter_area * min(dt_height, gt_height) - iou_3d = inter_volume / (dt_volume + gt_volume - inter_volume) - return iou_3d - - -def calc_IoU_floorplan(dt_floorplan, gt_floorplan, dt_height, gt_height): - dt_area, gt_area, inter_area = calc_inter_area_floorplan(dt_floorplan, gt_floorplan) - iou_2d = inter_area / (gt_area + dt_area - inter_area) - - dt_volume = dt_area * dt_height - gt_volume = gt_area * gt_height - inter_volume = inter_area * min(dt_height, gt_height) - iou_3d = inter_volume / (dt_volume + gt_volume - inter_volume) - return iou_2d, iou_3d - - -if __name__ == '__main__': - from visualization.floorplan import draw_floorplan, draw_iou_floorplan - from visualization.boundary import draw_boundaries, corners2boundaries - from utils.conversion import uv2xyz - from utils.height import height2ratio - - # dummy data - dt_floor_corners = np.array([[0.2, 0.7], - [0.4, 0.7], - [0.6, 0.7], - [0.8, 0.7]]) - dt_height = 2.8 - - gt_floor_corners = np.array([[0.3, 0.7], - [0.5, 0.7], - [0.7, 0.7], - [0.9, 0.7]]) - gt_height = 3.2 - - dt_xz = uv2xyz(dt_floor_corners)[..., ::2] - gt_xz = uv2xyz(gt_floor_corners)[..., ::2] - - dt_floorplan = draw_floorplan(dt_xz, show=False, show_radius=1) - gt_floorplan = draw_floorplan(gt_xz, show=False, show_radius=1) - # dt_floorplan = draw_floorplan(dt_xz, show=False, show_radius=2) - # gt_floorplan = draw_floorplan(gt_xz, show=False, show_radius=2) - - iou_2d, iou_3d = calc_IoU_floorplan(dt_floorplan, gt_floorplan, dt_height, gt_height) - print('use floor plan image:', iou_2d, iou_3d) - - iou_2d, iou_3d = calc_IoU(dt_xz, gt_xz, dt_height, gt_height) - print('use floor plan polygon:', iou_2d, iou_3d) - - draw_iou_floorplan(dt_xz, gt_xz, show=True, iou_2d=iou_2d, iou_3d=iou_3d) - pano_bd = draw_boundaries(np.zeros([512, 1024, 3]), corners_list=[dt_floor_corners], - boundary_color=[0, 0, 1], ratio=height2ratio(dt_height), draw_corners=False) - pano_bd = draw_boundaries(pano_bd, corners_list=[gt_floor_corners], - boundary_color=[0, 1, 0], ratio=height2ratio(gt_height), show=True, draw_corners=False) diff --git a/spaces/zhoujiaxin/zhoujiaxinchatgpt/src/components/chat-panel.tsx b/spaces/zhoujiaxin/zhoujiaxinchatgpt/src/components/chat-panel.tsx deleted file mode 100644 index 1fbc3c2bf05b914e0c229661832fbb560745f488..0000000000000000000000000000000000000000 --- a/spaces/zhoujiaxin/zhoujiaxinchatgpt/src/components/chat-panel.tsx +++ /dev/null @@ -1,153 +0,0 @@ -'use client' - -import * as React from 'react' -import Image from 'next/image' -import Textarea from 'react-textarea-autosize' -import { useAtomValue } from 'jotai' -import { useEnterSubmit } from '@/lib/hooks/use-enter-submit' -import { cn } from '@/lib/utils' - -import BrushIcon from '@/assets/images/brush.svg' -import ChatIcon from '@/assets/images/chat.svg' -import VisualSearchIcon from '@/assets/images/visual-search.svg' -import SendIcon from '@/assets/images/send.svg' -import PinIcon from '@/assets/images/pin.svg' -import PinFillIcon from '@/assets/images/pin-fill.svg' - -import { useBing } from '@/lib/hooks/use-bing' -import { voiceListenAtom } from '@/state' -import Voice from './voice' -import { ChatImage } from './chat-image' -import { ChatAttachments } from './chat-attachments' - -export interface ChatPanelProps - extends Pick< - ReturnType, - | 'generating' - | 'input' - | 'setInput' - | 'sendMessage' - | 'resetConversation' - | 'isSpeaking' - | 'attachmentList' - | 'uploadImage' - | 'setAttachmentList' - > { - id?: string - className?: string -} - -export function ChatPanel({ - isSpeaking, - generating, - input, - setInput, - className, - sendMessage, - resetConversation, - attachmentList, - uploadImage, - setAttachmentList -}: ChatPanelProps) { - const inputRef = React.useRef(null) - const {formRef, onKeyDown} = useEnterSubmit() - const [focused, setFocused] = React.useState(false) - const [active, setActive] = React.useState(false) - const [pin, setPin] = React.useState(false) - const [tid, setTid] = React.useState() - const voiceListening = useAtomValue(voiceListenAtom) - - const setBlur = React.useCallback(() => { - clearTimeout(tid) - setActive(false) - const _tid = setTimeout(() => setFocused(false), 2000); - setTid(_tid) - }, [tid]) - - const setFocus = React.useCallback(() => { - setFocused(true) - setActive(true) - clearTimeout(tid) - inputRef.current?.focus() - }, [tid]) - - React.useEffect(() => { - if (input) { - setFocus() - } - }, [input]) - - return ( -
    { - e.preventDefault() - if (generating) { - return; - } - if (!input?.trim()) { - return - } - setInput('') - setPin(false) - await sendMessage(input) - }} - ref={formRef} - > -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    - chat -

' : '\U0001d4ab', - '\\' : '\U0001d4ac', - '\\' : '\U0000211b', - '\\' : '\U0001d4ae', - '\\' : '\U0001d4af', - '\\' : '\U0001d4b0', - '\\' : '\U0001d4b1', - '\\' : '\U0001d4b2', - '\\' : '\U0001d4b3', - '\\' : '\U0001d4b4', - '\\' : '\U0001d4b5', - '\\' : '\U0001d5ba', - '\\' : '\U0001d5bb', - '\\' : '\U0001d5bc', - '\\' : '\U0001d5bd', - '\\' : '\U0001d5be', - '\\' : '\U0001d5bf', - '\\' : '\U0001d5c0', - '\\' : '\U0001d5c1', - '\\' : '\U0001d5c2', - '\\' : '\U0001d5c3', - '\\' : '\U0001d5c4', - '\\' : '\U0001d5c5', - '\\' : '\U0001d5c6', - '\\' : '\U0001d5c7', - '\\' : '\U0001d5c8', - '\\